The event
- Add click events
- Add the long press event
code
import Foundation
import UIKit
// MARK: - Add click events or long press events
typealias LabelAction = (UILabel) - > ()typealias LongPressAction = (UIGestureRecognizer) - > ()extension UILabel {
private struct AssociatedKeys{
static var actionKey = "actionKey"
static var longPressKey = "longPressKey"
}
@objc dynamic var action: LabelAction? {
set{
objc_setAssociatedObject(self.&AssociatedKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)}get{
if let action = objc_getAssociatedObject(self.&AssociatedKeys.actionKey) as? LabelAction{
return action
}
return nil}}@objc dynamic var longPressAction: LongPressAction? {
set{
objc_setAssociatedObject(self.&AssociatedKeys.longPressKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)}get{
if let action = objc_getAssociatedObject(self.&AssociatedKeys.longPressKey) as? LongPressAction{
return action
}
return nil}}@objc func clickAction(a) {
self.action?(self)}@objc func longPressGesture(sender:UIGestureRecognizer) {
self.longPressAction?(sender);
}
/// Add click events
/// -parameter action: callback event
func addClickAction(action: @escaping LabelAction) {
self.isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(clickAction))
self.action = action
self.addGestureRecognizer(gesture)
}
/// Add the long press event
/// -parameter action: callback event
func addLongPressAction(action: @escaping LongPressAction) {
self.isUserInteractionEnabled = true
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture))
self.longPressAction = action
self.addGestureRecognizer(gesture)
}
}
Copy the code
Demo: Github