Created
January 10, 2017 23:49
-
-
Save ccabanero/e8f529e9ac5da28a47fafc144f2d9f72 to your computer and use it in GitHub Desktop.
Swift 3 Protocol Pattern Snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// set up - MapViewController is the parent. A ContainerView is used to place the UI for directions - part of the DirectionsViewController. | |
// The DirectionsViewController has a protocol method for letting the delegate know when a user has tapped the 'get directions' button and passes the to and from data | |
// this ViewController is the delegate for the DirectionsViewController | |
Class MapViewController: UIViewController, DirectionsViewControllerDelegate { | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
// for getting access to the DirectionsViewController and settings its delegate as THIS controller | |
if segue.identifier == segueIdToDirectionsVC { | |
if let destinationVC = segue.destination as? DirectionsViewController { | |
destinationVC.delegate = self | |
} | |
} | |
} | |
func didRequestDirections(locations: (from: String, to: String)) { | |
print("user tapped - get directions | to: \(locations.from) and from: \(locations.to)") | |
} | |
} | |
.... | |
protocol DirectionsViewControllerDelegate: class { | |
func didRequestDirections(locations: (from: String, to: String)) | |
} | |
class DirectionsViewController: UIViewController { | |
weak var delegate: DirectionsViewControllerDelegate? | |
@IBOutlet weak var fromTextField: UITextField! | |
@IBOutlet weak var toTextField: UITextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
// MARK: - Directions | |
@IBAction func handleDirectionsButtonTap(_ sender: Any) { | |
if let fromText = fromTextField.text, let toText = toTextField.text { | |
delegate?.didRequestDirections(locations: (from: fromText, to: toText)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment