Last active
January 13, 2016 23:08
-
-
Save marcopompei/8ea278cc1478c6ef5de6 to your computer and use it in GitHub Desktop.
Using Protocol Extensions for reusable behavior
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
| protocol RequestPresenter: class { | |
| var loadingView: UIView? { get set } | |
| func retryRequest(sender: UIButton) | |
| } | |
| extension RequestPresenter where Self: UIViewController { | |
| func startedLoading() { | |
| let activityIndicator = UIActivityIndicatorView() | |
| addLoadingView(activityIndicator) | |
| activityIndicator.startAnimating() | |
| } | |
| func failedLoading() { | |
| let retryButton = UIButton() | |
| retryButton.setTitle("Retry", forState: .Normal) | |
| retryButton.addTarget(self, action: Selector("retryRequest:"), forControlEvents: .TouchUpInside) | |
| addLoadingView(retryButton) | |
| } | |
| func finishedLoading() { | |
| loadingView?.removeFromSuperview() | |
| loadingView = nil | |
| } | |
| func addLoadingView(newView: UIView) { | |
| loadingView?.removeFromSuperview() | |
| loadingView = newView | |
| view.addSubview(newView) | |
| newView.addConstraint(NSLayoutConstraint(item: newView, | |
| attribute: .CenterX, | |
| relatedBy: .Equal, | |
| toItem: view, | |
| attribute: .CenterX, | |
| multiplier: 1, | |
| constant: 0)) | |
| newView.addConstraint(NSLayoutConstraint(item: newView, | |
| attribute: .CenterY, | |
| relatedBy: .Equal, | |
| toItem: view, | |
| attribute: .CenterY, | |
| multiplier: 1, | |
| constant: 0)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment