This tutorial takes you through a simple application with two view controllers. Once which collects some data, and one which displays the data. A protocol and delegation is used to pass the data between the two view controllers.
This view controller will be used to collect some data (a String) from the user.
Ideally it should be able to return that data to any view controller, or indeed an instance of another type of class, so we dont want it to have a reference to any specific view controller in its code, as this would impede reusability. Instead, we want to be able to delegate responsibility to any view controller capable of receiving the data
Within the DataCollectionViewController file, but outside the class, add the following code:
protocol DataCollectionViewControllerDelegate {
func dataUpdated(userText: String)
}
Any class adopting this prtocol would be able to be notified when the data in a DataCollectionViewController is updated
var delegate : DataCollectionViewControllerDelegate?
This property will represent the delegate. The delegate is an optional as it might not existdoneButtonPressed()
method to notify the delegate of the new data, before the view is dismissed:
delegate?.dataUpdated(userText: textField.text!)
Note that the method would only be called if the delegate exists (the ?
ensures this)DataCollectionViewControllerDelegate
protocol. Open that file and modify the delcaration of the class to that it adops the delegate as follows:
class ViewController: UIViewController, DataCollectionViewControllerDelegate {
//code etc.
}
func dataUpdated(userText: String) {
}
displayLabel.text = userText
prepare(for segue, sender)
method
if let destination = segue.destination as? DataCollectionViewController {
destination.delegate = self
}