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

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)
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容