常用的四种传值方法:单例,代理,闭包,通知(一)
(例如:从页面a,反向传值(这里是背景颜色backgroundColor)到页面b)
1.单例
1>.创建单例变量 在AppDelegate.swift 中创建变量var backgroundColor:UIColor?
2>在页面a中创建单例对象:
func changeBlue(){
let appDele = UIApplication.sharedApplication().delegate as! AppDelegate
appDele.backgroundColor = UIColor.blueColor()
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let appDele = UIApplication.sharedApplication().delegate as! AppDelegate
self.view.backgroundColor = appDele.backgroundColor
}
/*扩展一下代理的使用步骤:
代理和协议的使用
A.delegate = B
3 2 1
A:
1)确定谁是A
2)A.delegate = ****
3)A.delegate调用代理方法
delegate:
1)定义一个协议和对应的方法
2)声明delegate的属性
B:
1)B(firstCtrl)遵守协议,实现代理方法
*/
2)A.delegate = ****
func clickBtn(){
let secondCtrl = SecondViewController()
//设置代理
secondCtrl.delegate = self
self.presentViewController(secondCtrl, animated: true, completion: nil)
}
3)A.delegate 调用代理方法func backAction(){
//调用代理属性的方法
self.delegate?.sendValue((self.label?.text)!)
self.dismissViewControllerAnimated(true, completion: nil)
}
protocol SecondViewControllerDelegate {
func sendValue(text: String)
}
2)声明delegate的属性
//代理属性
var delegate: SecondViewControllerDelegate?
1)B(firstCtrl) 遵守协议,实现代理方法class FirstViewController: UIViewController, SecondViewControllerDelegate {}
//MARK: SecondViewController的代理
extension FirstViewController{
func sendValue(text: String) {
self.label?.text = text
}
}