ActionKit
ActionKit 是一个轻量级、易于使用的框架,它将目标-动作设计范式封装在一个更加简洁的格式中。它通过去掉目标并使用闭包替换选择器来缩短目标-动作方法调用。
没有 ActionKit 的目标-动作示例
button.addTarget(self, action: #selector(MyViewController.buttonWasTapped(_:)), forControlEvents: .TouchUpInside)
以及其他地方...
func buttonWasTapped(sender: Any) {
if let button = sender as? UIButton {
button.setTitle("Button was tapped!", forState: .Normal)
}
}
或者使用 ActionKit,一切都在一个地方
button.addControlEvent(.touchUpInside) { (control: UIControl) in
guard let button = control as? UIButton else {
return
}
button.setTitle("Button was tapped!", forState: .Normal)
}
安装
CocoaPods
ActionKit 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'ActionKit', '~> 2.5.2'
Carthage
-
- 将以下内容添加到您的 Cartfile
github "ActionKit/ActionKit" == 2.5.2
-
- 运行
carthage update
- 运行
-
- 按照 Carthage Readme 中的说明添加框架
工作原理
ActionKit 通过提供易于使用的方法并使用闭包(而不是选择器)来扩展目标操作功能。ActionKit 使用单例模式,单例存储闭包并充当目标。闭包捕获并存储其上下文中的任何常量和变量的引用,因此用户可以在定义闭包的上下文中使用变量。
特性
- 向任何
UIGestureRecognizer
子类(例如UITapGestureRecognizer
、UIPanGestureRecognizer
等)添加基于闭包的操作,而不是需要使用目标操作机制 - 从
UIGestureRecognizer
子类中删除添加的动作 - 向任何
UIControl
子类(例如:UIButton
、UIView
、UISwitch
等)添加基于闭包的操作,而不是需要使用目标操作机制 - 对于
UIControl
,为任何数量的controlEvent
添加操作 - 从
UIControl
子类中删除添加的动作 - 向任何
UIBarButtonItem
添加基于闭包的操作,而不是需要目标操作 - 从
UIBarButtonItem
中删除添加的动作
示例
请见例子维基
变更日志
请见此处
许可协议
在MIT许可下授权。请查阅LICENSE文件