Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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.backgroundColo

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

大佬总结

以上是大佬教程为你收集整理的Swift 正向传值以及利用闭包(closure)实现反向传值(七)全部内容,希望文章能够帮你解决Swift 正向传值以及利用闭包(closure)实现反向传值(七)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: