Switchcraft
内容
描述
Switchcraft是一个简单的工具,旨在使在不同末端之间切换变得轻而易举。
它被设计成可以被放入现有的项目中并忘记,但同时也支持配置多个实例以及许多其他酷炫的功能。
用法
管理单个实例
使用 Switchcraft 最简单的方法是声明一个全局实例,我们建议在您的 AppDelegate.swift
中声明,如下所示:
extension Switchcraft {
static let shared = Switchcraft(config: /*..*/)
}
然后,从您想要显示选择器的 ViewController 中,您只需要将 Switchcraft
手势识别器附加到一个视图控制器
Switchcraft.shared.attachGesture(to: self)
然后您可以在任何地方使用以下方法检索当前端点
Switchcraft.shared.endpoint
要查看此功能如何工作,请参阅 ReallySimpleExampleVC。
保持当前状态
当选择端点时,您有两个选项来获取更新:
-
委托
如果您只需要在单个位置跟踪当前端点的更改,这可能是您的最佳选择。想要接收更新并获得通知的类只需要将您的
viewController
作为委托并实现SwitchcraftDelegate
协议。class MyVC: UIViewController { // ... override func viewDidLoad() { super.viewDidLoad() Switchcraft.delegate = self } } extension MyVC: SwitchcraftDelegate { func switchcraft(_ switchcraft: Switchcraft, didSelectEndpoint endpoint: Endpoint) { // Handle your endpoint selection here } }
-
通知中心
端点选择也会广播到
NotificationCenter
。NotificationCenter.default.addObserver(self, selector: #selector(endpointSelected(_:)), name: .SwitchcraftDidSelectEndpoint, object: nil) ... @objc private func endpointSelected(_ sender: NSNotification) { guard let endpoint = sender.userInfo?[Notification.Key.Endpoint] as? Endpoint else { return } // Handle endpoint selected here }
自定义动作
- 通过
Config
向 Switchcraft 添加一些自定义动作
extension Switchcraft {
static let shared = Switchcraft(config: Config(
defaultsKey: ...,
endpoints: ...,
actions: [
Action(title: "Custom action 1", actionId: "customAction1"),
Action(title: "Custom action 2", actionId: "customAction2")
]
))
}
- 在 SwitchCraftDelegate 中添加以下内容:
extension MyVC: SwitchcraftDelegate {
...
func switchcraft(_ switchcraft: Switchcraft, didTapAction action: Action)
// Handle custom action selection here
}
}
注意:我们建议使用 Swift 枚举作为 actionId,如以下示例所示:
enum Actions: String {
case custom1
case custom2
}
extension Switchcraft {
static let shared = Switchcraft(config: Config(
defaultsKey: ...,
endpoints: ...,
actions: [
Action(title: "Custom action 1", actionId: Actions.custom1.rawValue),
Action(title: "Custom action 2", actionId: Actions.custom2.rawValue)
]
))
}
extension MyVC: SwitchcraftDelegate {
...
func switchcraft(_ switchcraft: Switchcraft, didTapAction action: Action) {
guard let action = Actions(rawValue: action.actionId) else {
return
}
switch action {
case .custom1:
// handle the first custom action tapped
...
case .custom2:
// handle the second custom action tapped
...
}
}
}
变得复杂
您可以在配置中调整很多功能。有关完整列表,请参阅 Config.swift。
示例
要运行示例项目,请克隆存储库,然后从 Example 目录运行 pod install
。
要求
- iOS 9.3 或更高版本
- Xcode 10 或更高版本
- Swift 4.2 或更高版本
安装
Swift 包管理器
Switchcraft 通过 Swift 包管理器提供。要安装它,请按照以下步骤操作
- 在 Xcode 中,点击文件,然后选择 Swift 包管理器,然后添加包依赖项
- 选择您的项目
- 在搜索栏中输入此 URL https://github.com/steamclock/switchcraft.git
CocoaPods
Switchcraft 同样可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod 'Switchcraft'
作者
许可
Switchcraft 采用 MIT 许可。有关更多信息,请参阅 LICENSE 文件。