加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 07:09:43 所属栏目:百科 来源:网络整理
导读:直接上代码吧 - - Demo地址 https://github.com/Zhangjingwang1993/closureDemo.git // MainVclet button = UIButton .init (type: UIButtonType .Custom )button .frame = CGRectMake( 20 , 100 , 50 , 50 ) ; button .backgroundColor = UIColor .cyanColo

直接上代码吧 - -
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)
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读