Swift 協議和委託(代理),swift委託
協議 (Protocols)
用於統一方法和屬性的名稱,而不實現任何功能,能夠被類、枚舉、結構體實現,滿足協議要求的都成為協議的遵循者,遵循者需要提供協議指定的成員,如方法,屬性,操作符,下標
文法protocol SomeProtocol {// protocol definition goes here} // 中間以冒號分隔實現協議,有多個協議的話,協議之間逗號分隔struct SomeStructure: FirstProtocol, AnotherProtocol {// structure definition goes here} // 含有父類的同時實現協議,父類寫在協議之前class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {// class definition goes here}
委託(代理)模式
委託是一種設計模式,它允許類或結構體將一些需要它們負責的功能交由(委託)
給其他的類型。
委託模式的實現很簡單: 定義協議
來封裝
那些需要被委託的函數和方法
, 使其遵循者
擁有這些被委託的函數和方法
。
委託模式可以用來響應特定的動作或接收外部資料源提供的資料,而無需要知道外部資料源的類型
文法
FirstViewController的代碼
class FirstViewController: UIViewController, SecondViewControllerDelegate { @IBOutlet weak var showDelegateTextLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //點擊按鈕跳轉到SecondViewController @IBAction func tapGoSecondViewController(sender: UIButton) { //從storyboard上載入SecondViewController let secondVC = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController secondVC.delegate = self //跳轉到SecondViewController self.navigationController?.pushViewController(secondVC, animated: true) } //MARK: - SecondViewControllerDelegate func fetchBackString(str: String) { self.showDelegateTextLabel.text = str } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
SecondViewController的代碼
import UIKitprotocol SecondViewControllerDelegate: NSObjectProtocol{ func fetchBackString(str: String)}class SecondViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! weak var delegate: SecondViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func delegateBackMethod(sender: UIButton) { if self.delegate != nil { if let tempString = self.inputTextField.text { delegate!.fetchBackString("代理返回資料:\(tempString)") } } self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}