Swift 正向传值以及利用闭包(closure)实现反向传值(七)

前端之家收集整理的这篇文章主要介绍了Swift 正向传值以及利用闭包(closure)实现反向传值(七)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

直接上代码吧 - -
Demo地址
https://github.com/Zhangjingwang1993/closureDemo.git

// MainVc
let button = UIButton.init(type: UIButtonType.Custom)
button.frame = CGRectMake(20,100,50,50);
button.backgroundColor = UIColor.cyanColor()
self.view.addSubview(button)
button.addTarget(self,action: Selector("click:"),forControlEvents: UIControlEvents.TouchUpInside)

textField = UITextField.init(frame: CGRectMake(20,160,50));
self.view.addSubview(textField)
textField.placeholder = "I am Placehoder"
func addressThatTakesAClosure(string:String) ->Void{
        textField.text = string
    }
func click(sender: UIButton)
    {
        // 初始化
        let sec = MainViewController()
        // 类似于属性传值
        sec.string = "Success"

        /***********************************************/
        // ---------------华丽的分割线---------------- //
        // 用函数把地址传过去,用于回调
        // sec.initWithClosure(addressThatTakesAClosure)
        // 或者直接这样
        sec.myClosure = addressThatTakesAClosure
        self.navigationController?.pushViewController(sec,animated: true)
    }
// SecVc
// 类似于OC中的typedef
    typealias sendValueClosure = (string:String)->Void
var string = ""
    // 声明一个Closure(闭包)
    var myClosure:sendValueClosure?
    // 下面这个方法需要传入上个界面的addressThatTakesAClosure函数指针
    func initWithClosure(closure:sendValueClosure?){
        myClosure = closure
    }
// 类似于OC中的属性传值
    print("Success: \(string)")
    let label = UILabel.init(frame: CGRectMake(10,150,30))
    label.text = string
    self.view.addSubview(label)
func backButtonCreate()
    {
        // 返回按钮
     var buttonRight = UIButton()
     buttonRight = UIButton.init(type: UIButtonType.Custom)
     buttonRight.backgroundColor = UIColor.redColor()
     buttonRight.frame = CGRectMake(280,50)
     self.view.addSubview(buttonRight)
     buttonRight.setTitle("返回",forState: UIControlState.Normal)
     buttonRight.addTarget(self,action: Selector("click"),forControlEvents: UIControlEvents.TouchUpInside)
    }
// 返回点击方法
func click()
    {
        if myClosure != nil{
            myClosure!(string: string);
        }                                                    self.navigationController?.popToRootViewControllerAnimated(true)
    }
原文链接:https://www.f2er.com/swift/324292.html

猜你在找的Swift相关文章