AlertReactor 是一个针对 UIAlertController 的 ReactorKit 扩展。它提供了一种优雅的方式来处理 UIAlertController。 如果您有延迟加载的警报操作,则最适合使用它。
这是一个 AlertReactor
的示例实现
final class UserAlertReactor: AlertReactor<UserAlertAction> {
override func mutate(action: Action) -> Observable<Mutation> {
switch action {
case .prepare:
return .just(.setActions([.copy, .follow, .block, .cancel]))
case let .selectAction(alertAction):
switch alertAction {
case .copy: return foo()
case .follow: return foo()
case .unfollow: return foo()
case .block: return foo()
case .cancel: return foo()
}
}
}
}
首先,您应该定义一个符合 AlertActionType
协议的新类型。 这是 UIAlertAction
的一个抽象模型。 此协议需要一个 title
(必需),style
(可选)和 isEnabled
(可选)属性。
enum UserAlertAction: AlertActionType {
case loading
case follow
case block
case cancel
// required
var title: String {
switch self {
case .loading: return "Loading"
case .follow: return "Follow"
case .block: return "Block"
case .cancel: return "Cancel"
}
}
// optional
var style: UIAlertActionStyle {
switch self {
case .loading: return .default
case .follow: return .default
case .block: return .destructive
case .cancel: return .cancel
}
}
// optional
var isEnabled: Bool {
switch self {
case .loading: return false
default: return true
}
}
}
AlertReactor
是一个泛型 reactor 类。它接受一个符合 AlertActionType
协议的泛型类型。 此 reactor 提供了一个默认的 action、mutation 和 state。 这是 AlertReactor
的一个简化定义。 您可以继承此类并覆盖 mutate(action:)
方法以实现特定的业务逻辑。
class AlertReactor<AlertAction: AlertActionType>: Reactor {
enum Action {
case prepare // on viewDidLoad()
case selectAction(AlertAction) // on select action
}
enum Mutation {
case setTitle(String?)
case setMessage(String?)
case setActions([AlertAction])
}
struct State {
public var title: String?
public var message: String?
public var actions: [AlertAction]
}
}
我们将使用 UserAlertAction
作为泛型参数来创建一个新的 AlertReactor
子类。
final class UserAlertReactor: AlertReactor<UserAlertAction> {
override func mutate(action: Action) -> Observable<Mutation> {
switch action {
case .prepare:
return .just(Mutation.setActions([.copy, .follow, .block, .cancel]))
case let .selectAction(alertAction):
switch alertAction {
case .loading: return .empty()
case .follow: return UserAPI.follow()
case .block: return UserAPI.block()
case .cancel: return .empty()
}
}
}
}
AlertController
是 UIAlertController
的一个子类,它符合 ReactorKit 中的 View
协议。 此类还接受一个 AlertActionType
的泛型类型。 您可以使用一些可选参数来初始化此类:reactor
和 preferredStyle
。 只需呈现它,然后 reactor 将为您处理业务逻辑。
let reactor = UserAlertReactor()
let controller = AlertController<UserAlertAction>(reactor: reactor, preferredStyle: .actionSheet)
self.present(controller, animated: true, completion: nil)
pod 'AlertReactor'
AlertReactor 基于 MIT 许可证。 请参阅 LICENSE 了解更多信息。