Skip to content

Instantly share code, notes, and snippets.

@marcopompei
Last active January 13, 2016 23:08
Show Gist options
  • Select an option

  • Save marcopompei/8ea278cc1478c6ef5de6 to your computer and use it in GitHub Desktop.

Select an option

Save marcopompei/8ea278cc1478c6ef5de6 to your computer and use it in GitHub Desktop.
Using Protocol Extensions for reusable behavior
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