-
Notifications
You must be signed in to change notification settings - Fork 3
iOS Delegation
Kevin Leong edited this page Oct 27, 2016
·
1 revision
class ViewController: UIViewController, ModalViewDelegate {
// Tapping the button displays the modal
@IBAction func didTapButton(sender: UIButton) {
let modal = ModalViewController()
// Remember to set the delegate
modal.delegate = self
// Display the modal
presentViewController(modal, animated: true, completion: nil)
}
func dismissModal(modal: ModalViewController?) {
dismissViewControllerAnimated(true, completion: nil)
}
}
// `class` indicates only classes may implement this protocol
protocol ModalViewDelegate: class {
// Common practice is to pass the sender to the delegate
func dismissModal(sender: ModalViewController?)
}
class ModalViewController: UIViewController {
/*
Use a weak reference so that this doesn't keep the delegate from
being garbage collected.
*/
weak var delegate: ModalViewDelegate?
override func loadView() {
// CGRectZero is equivalent to CGRectMake(0, 0, 0, 0)
let view = UIView(frame: CGRectZero)
view.backgroundColor = UIColor.redColor()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ModalViewController.didTap))
view.addGestureRecognizer(tapGestureRecognizer)
self.view = view
}
func didTap() {
delegate?.dismissModal(self)
}
}