Skip to content

Instantly share code, notes, and snippets.

@ccabanero
Created January 10, 2017 23:49
Show Gist options
  • Select an option

  • Save ccabanero/e8f529e9ac5da28a47fafc144f2d9f72 to your computer and use it in GitHub Desktop.

Select an option

Save ccabanero/e8f529e9ac5da28a47fafc144f2d9f72 to your computer and use it in GitHub Desktop.

Revisions

  1. ccabanero created this gist Jan 10, 2017.
    53 changes: 53 additions & 0 deletions Swift 3 Protocol Pattern Snippet
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@

    // 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))
    }
    }
    }