美文网首页
四种传值方法:单例,代理,闭包,通知

四种传值方法:单例,代理,闭包,通知

作者: 彧哥哥 | 来源:发表于2022-02-09 22:29 被阅读0次

    3.闭包

    1>在a页的视图控制器中声明一个闭包

    //声明闭包
    var closure:((UIColor)->())?

    2>在b页的视图控制器中创建闭包方法,并调用

    func clickBtn(){
    let tmpViewCtrl =TmpViewController()
    print(tmpViewCtrl)
    //创建闭包方法
    tmpViewCtrl.closure = {
    (backgroundColor:UIColor)->()in
    self.view.backgroundColor = backgroundColor
    }
    self.presentViewController(tmpViewCtrl, animated:true, completion: nil)
    }
    3>创建闭包实例
    在b页的视图控制器中:

    func changeRed(){
    self.closure!(UIColor.redColor())
    self.dismissViewControllerAnimated(true, completion: nil)
    }

    4.通知

    1>在a页面中,创建观察者属性以及收到通知后的响应notiAction

    //定义观察者属性

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "notiAction:", name:"changeBackgroundColor", object:nil)
    //响应方法,传入初值
    func notiAction(n:NSNotification){
    let dic = n.userInfoas! [String:NSObject]
    let bgColor = dic["backgroundColor"]as! UIColor
    self.view.backgroundColor = bgColor
    }

    2>在b页面设置通知属性,发送发通知

    func changeRed(){
    //发送通知并传入数值
    NSNotificationCenter.defaultCenter().postNotificationName("changeBackgroundColor", object: nil, userInfo: ["backgroundColor":UIColor.redColor()])
    self.dismissViewControllerAnimated(true, completion: nil)
    }

    相关文章

      网友评论

          本文标题:四种传值方法:单例,代理,闭包,通知

          本文链接:https://www.haomeiwen.com/subject/zmmgkrtx.html