直接上代码,代码中有注释 第一种写法
lazy var tapGestureRecognizer: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:)))
return tap
}()
var lastTapTime:TimeInterval = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
self.view.addGestureRecognizer(tapGestureRecognizer)
}
@objc func tapAction(tap:UITapGestureRecognizer) {
let point = tap.location(in: self.view)
print(point)
let time = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if time - lastTapTime > 0.25 {
self.perform(#selector(sigleTapAction), with: nil, afterDelay: 0.25)
}else {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(sigleTapAction), object: nil)
print("双击手势")
}
lastTapTime = time
}
@objc func sigleTapAction() {
print("单击手势")
}
第二种写法
lazy var tapGestureRecognizer: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:)))
tap.numberOfTapsRequired = 1
return tap
}()
lazy var tapGestureRecognizer2: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction2(tap:)))
tap.numberOfTapsRequired = 2
return tap
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
tapGestureRecognizer.require(toFail: tapGestureRecognizer2)
self.view.addGestureRecognizer(tapGestureRecognizer)
self.view.addGestureRecognizer(tapGestureRecognizer2)
}
@objc func tapAction(tap:UITapGestureRecognizer) {
print("单击---手势")
}
@objc func tapAction2(tap:UITapGestureRecognizer) {
print("双击---手势")
}
|