问题描述
在下面的代码中,我有一个ViewController
("SenderViewController"),当点击一个按钮时,它将消息传递到主ViewController
.我还不完全了解主ViewController
中的messageData()
方法如何知道何时收听消息.
In the code below I have a ViewController
("SenderViewController"), which passes a message to the main ViewController
when a button is tapped. What I don't fully understand is how does messageData()
method in the main ViewController
know when to listen for the message.
有人可以解释一下什么触发了主ViewController
中的messageData()
方法吗?
Can someone please explain me what is triggering the messageData()
method in the main ViewController
?
SenderViewController:
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:
Main 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)"
}
}
非常感谢!
推荐答案
对象不完全侦听方法调用.他们坐在那里,等待被调用.
Objects don't exactly listen for method calls. They sit there, waiting to invoked.
行
self.delegate?.messageData(inputMessage.text!)
在您的SenderViewController
中是一个函数调用. (尽管方法method
通常用于对象的功能,但是术语方法和功能几乎可以互换.)它在ViewController
中调用函数messageData.
From your SenderViewController
is a function call. (The term method and function are pretty much interchangeable, although the method
is usually used for the functions of objects.) It invokes the function messageData in ViewController
.
这篇关于如何使用协议/代理在UIViewController之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!