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