在下面的代碼中,我有一個ViewController
(「SenderViewController」),它在點擊按鈕時將消息傳遞給主要的ViewController
。我不完全明白的是messageData()
方法在主要的ViewController
中知道何時收聽消息。如何通過協議/代理在UIViewControllers之間傳遞數據
有人能解釋一下,在主ViewController
中觸發messageData()
方法是什麼?
SenderViewController:
import UIKit
protocol SenderViewControllerDelegate {
func messageData(data: AnyObject)
}
class SenderViewController: UIViewController {
@IBOutlet weak var inputMessage: UITextField!
var delegate: SenderViewControllerDelegate?
@IBAction func sendData(sender: AnyObject) {
/
if inputMessage.text != ""{
self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
self.delegate?.messageData(inputMessage.text!)
}
}
}
主要的ViewController:
import UIKit
class ViewController: UIViewController, SenderViewControllerDelegate{
@IBOutlet weak var showData: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goToView(sender: AnyObject) {
let pvc = storyboard?.instantiateViewControllerWithIdentifier("senderViewController") as! SenderViewController
pvc.delegate = self
self.presentViewController(pvc, animated:true, completion:nil)
}
// What triggers this method, how it know when to listen?
func messageData(data: AnyObject) {
self.showData.text = "\(data)"
}
}
非常感謝!
這個調用'self.delegate?.messageData'來自'SenderViewController'中的'func sendData'正在執行它。 – iphonic
按照本教程,您將得到您的答案 - http://www.tutorialspoint.com/ios/ios_delegates.htm –
使用委託swift 4.0傳遞數據:https://iosdevcenters.blogspot.com/2017/11/what- is-protocol-how-to-pop-data-using.html – Bhadresh