Last active
November 17, 2017 14:15
-
-
Save yoman07/b0070b526893e50d2c42594cd4499691 to your computer and use it in GitHub Desktop.
Alert view controller abstraction
This file contains 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
import Foundation | |
final class AlertViewControllerBuilder { | |
var title: String? | |
var message: String? | |
var okHandler: AnonymousActionClosure? | |
var cancelHandler: AnonymousActionClosure? | |
typealias BuilderClosure = (AlertViewControllerBuilder) -> Void | |
init(_ buildClosure: BuilderClosure) { | |
buildClosure(self) | |
} | |
} | |
final class AlertViewControllerImpl: AlertViewController { | |
private var alert: UIAlertController | |
init(_ builder: AlertViewControllerBuilder) { | |
self.alert = UIAlertController(title: builder.title, message: builder.message, preferredStyle: .alert) | |
let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in | |
builder.okHandler?() | |
} | |
self.alert.addAction(okAction) | |
let cancelAction = UIAlertAction(title: NSLocalizedString("CANCEL", comment: ""), style: .default) { _ in | |
builder.cancelHandler?() | |
} | |
self.alert.addAction(cancelAction) | |
} | |
func show(viewControllerPresenting: UIViewController, animated: Bool, completion: (() -> Void)?) { | |
viewControllerPresenting.present(alert, animated: animated, completion: completion) | |
} | |
} | |
// Alert functionality should be limited to AlertViewController, revisit | |
typealias Alert = AlertViewControllerImpl | |
typealias AnonymousActionClosure = () -> Void | |
protocol AlertViewController { | |
init(_ builder: AlertViewControllerBuilder) | |
func show(viewControllerPresenting: UIViewController, animated: Bool, completion: (() -> Void)?) | |
} | |
let alertBuilder = AlertViewControllerBuilder({ builder in | |
builder.title = NSLocalizedString("GENERIC_ERROR_TITLE", comment: "") | |
builder.message = NSLocalizedString("GENERIC_LOADING_ERROR_MESSAGE", comment: "") | |
builder.okHandler = { self?.loadTopics() } | |
}) | |
self?.present(alert, animated: true, completion: nil) | |
Alert(alertBuilder).show(viewControllerPresenting: self!, animated: true, completion: nil) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment