OnGestureSwift
Android SDK 允许开发者将任何 View
对象设置一个 OnClickListener
对象,现在您也可以在 Swift 中这样做!使用这个 CocoaPod 项目,您可以将任何 UIView
对象与一个包含闭包内的动作的“监听器”关联起来。
此项目提供轻量级的 Swift 扩展,允许开发者使用 onGesture
方法,例如:onClick
、onLongPress
、onSwipe
、onPan
(甚至 onDrag
允许拖动视图)。
这与 Android SDK 的 setOnClickListener(...)
方法非常相似。
onClick(简单点击)的使用
import OnGestureSwift
...
someView.onClick() { (tapGestureRecognizer: UITapGestureRecognizer) in
// Do something...
}
onLongPress的使用
import OnGestureSwift
...
mapView.onLongPress({ [weak self] (longPressGestureRecognizer) in
guard longPressGestureRecognizer.state == .began, let mapView = self?.mapView else { return }
let longPressedLocationCoordinate = mapView.convert(longPressGestureRecognizer.location(in: mapView), toCoordinateFrom: mapView)
print("tapped on location's coordinate: \(longPressedLocationCoordinate)")
// Do stuff with 'longPressedLocationCoordinate'
})
onSwipe 使用
import OnGestureSwift
...
override func viewDidLoad() {
super.viewDidLoad()
view.onSwipe(direction: .down) { [unowned self] _ in
self.dismiss(animated: true, completion: nil)
}
...
}
onPan 使用
import OnGestureSwift
...
someButton.onPan { [weak self] (panGestureRecognizer) in
guard let strongSelf = self else { return }
if let superview = panGestureRecognizer.view?.superview {
let locationOfPan = panGestureRecognizer.location(in: superview)
// Do something with 'locationOfPan'
}
}
onDrag 使用
import OnGestureSwift
...
someLabel.onDrag(predicateClosure: { _ in
return true
}, onDragClosure: { dragGestureListener in
guard let draggingPoint = dragGestureListener.pannedPoint else { return }
// Do something with 'draggingPoint'
})
CocoaPods
要安装此库,只需执行以下命令:pod 'OnGestureSwift'
重要提示
内存管理
不用担心内存泄漏,这个实现已经被测试过,审查过,使用过并改进过 - 它与弱引用完美兼容。我之前尝试过使用 objc_setAssociatedObject
,但是我发现它会导致内存泄漏,所以不建议使用。选择的解决方案没有内存问题,所以请放心,放飞你的思想。 :)
只需确保在不需要对 self
保持强引用的情况下传递 [weak self] / [unowned self](你通常不希望在闭包内部保持强引用)。
//待办
- 我计划将全局 typealias CallbackClosure 及其“朋友”移入到一个命名空间,以避免与其他开发者的工具冲突。
祝您开心 :) Perry