我如何添加一个触摸事件到一个UIView?
我试一试:
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)] autorelease];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];
// ERROR MESSAGE: UIView may not respond to '-addTarget:action:forControlEvents:'
我不想创建一个子类然后重写
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
斯威夫特和斯威夫特
import UIKit
extension UIView {
func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
Use
yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))
斯威夫特5.3
基于闭包的UIGestureRecognizer解决方案
final class BindableGestureRecognizer: UITapGestureRecognizer {
private var action: () -> Void
init(action: @escaping () -> Void) {
self.action = action
super.init(target: nil, action: nil)
self.addTarget(self, action: #selector(execute))
}
@objc private func execute() {
action()
}
}
public extension UIView {
/// A discrete gesture recognizer that interprets single or multiple taps.
/// - Parameters:
/// - tapNumber: The number of taps necessary for gesture recognition.
/// - closure: A selector that identifies the method implemented by the target to handle the gesture recognized by the receiver. The action selector must conform to the signature described in the class overview. NULL is not a valid value.
func addTapGesture(tapNumber: Int = 1, _ closure: (() -> Void)?) {
guard let closure = closure else { return }
let tap = BindableGestureRecognizer(action: closure)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
使用:
view.addTapGesture { [weak self] in
self?.view.backgroundColor = .red
}