用协议在两个界面传递数据
2016-10-12 本文已影响10人
Dove_Q
ViewController
class ViewController: UIViewController, SecondViewControllerDelegate {
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func didClick(sender: UIButton) {
//1. 创建第二个页面的对象
let secondCtrl = SecondViewController()
//耦合:松/紧
secondCtrl.delegate = self
//2. 显示
self.presentViewController(secondCtrl, animated: true, completion: nil)
}
//通过函数参数从第二个页面返回数据
func didTouched(data: String?) {
print(data!)
}
//通过返回值给第二个页面传递数据
func fetchData() -> String {
return "yyyyy"
}
}
SecondViewControllerDelegate
protocol SecondViewControllerDelegate {
func didTouched(data: String?)
func fetchData() -> String
}
class SecondViewController: UIViewController {
var delegate: SecondViewControllerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
if delegate != nil {
let s = delegate.fetchData()
print("第二个页面: ", s)
}
self.view.backgroundColor = UIColor.redColor()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if delegate != nil {
delegate.didTouched("xxxx")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}