final class AlertViewComponent: UIAlertController {
private(set) var model: Model!
private let alert: UIAlertController
init() {
self.alert = UIAlertController(title: "abc", message: "def", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: L10n.Generic.Label.ok, style: .default, handler: nil))
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureAlert(options: AlertOption) {
self.alert.title = self.model.title
self.alert.message = self.model.message
switch options {
case let .oneOption(handler):
alert.addAction(UIAlertAction(title: L10n.Generic.Label.ok, style: .default, handler: handler))
case let .twoOptions(handlerYes, handlerNo):
alert.addAction(UIAlertAction(title: L10n.Generic.Label.ok, style: .default, handler: handlerYes))
alert.addAction(UIAlertAction(title: L10n.Generic.Label.yes, style: .default, handler: handlerNo))
}
}
}
extension AlertViewComponent: Component {
enum AlertOption {
case oneOption(handler: (UIAlertAction) -> Void)
case twoOptions(handlerYes: (UIAlertAction) -> Void, handlerNo: (UIAlertAction) -> Void)
}
struct Model {
let title: String
let message: String
init(title: String = "", message: String) {
self.title = title
self.message = message
}
}
enum Configuration {
case update(model: Model)
}
func render(with configuration: AlertViewComponent.Configuration) {
switch configuration {
case let .update(model):
self.model = model
}
}
}
我用以下方式初始化了警报。
private let alertViewComponent: AlertViewComponent = {
let alertViewComponent = AlertViewComponent()
alertViewComponent.render(with: .update(model: AlertViewComponent.Model(title: "title", message: "message")))
return alertViewComponent
}()
但当我显示该警报时,我得到了错误信息:
"UIAlertController必须有一个标题,一个消息或一个动作来显示
你从未调用过你的 configureAlert
函数。另外,你在子类中,也有一个警报控制器成员。哪一个得到了呈现?根本不需要子类alert controller--用你的成员就可以了。