FirstViewController的代碼
import UIKit
classFirstViewController: UIViewController, SecondViewControllerDelegate {
@IBOutletweak var showTextLabel: UILabel!
@IBOutletweak var showDelegateTextLabel: UILabel!
overridefunc viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//點(diǎn)擊按鈕跳轉(zhuǎn)到SecondViewController
@IBActionfunc tapGoSecondViewController(sender: UIButton) {
//從storyboard上加載SecondViewController
let secondVC = UIStoryboard(name:"Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController
//實(shí)現(xiàn)回調(diào)赴恨,獲取回調(diào)回來的值(閉包)
secondVC.backClosure = {
(backStr: String) -> Voidin
self.showTextLabel.text = backStr
}
secondVC.delegate =self
//跳轉(zhuǎn)到SecondViewController
self.navigationController?.pushViewController(secondVC, animated:true)
}
//MARK: - SecondViewControllerDelegate(代理)
func fetchBackString(str: String) {
self.showDelegateTextLabel.text = str
}
overridefunc didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
SecondViewController的代碼
import UIKit
//定義閉包類型(特定的函數(shù)類型函數(shù)類型)
typealias InputClosureType = (String) -> Void
protocol SecondViewControllerDelegate: NSObjectProtocol{
func fetchBackString(str: String)
}
class SecondViewController: UIViewController {
@IBOutletweak var inputTextField: UITextField!
//接收上個(gè)頁(yè)面?zhèn)鬟^來的閉包塊
var backClosure: InputClosureType?
weak var delegate: SecondViewControllerDelegate?
overridefunc viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBActionfunc tapBackButton(sender: UIButton) {
ifself.backClosure !=nil{
iflet tempString =self.inputTextField.text {
self.backClosure!(tempString)
}
}
self.navigationController?.popViewControllerAnimated(true)
}
@IBActionfunc delegateBackMethod(sender: UIButton) {
ifself.delegate !=nil{
iflet tempString =self.inputTextField.text {
delegate!.fetchBackString("代理返回?cái)?shù)據(jù):\(tempString)")
}
}
self.navigationController?.popViewControllerAnimated(true)
}
overridefunc didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}