UITapGestureRecognizer
点击手势, 可以设置单击,双击,多击,还可以设置使用几根手指, 下面我们学习如何使用它
1.UITapGestureRecognizer的创建
import UIKit
class ViewController: UIViewController {
var label: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
label = UILabel(frame: CGRect(x: 20, y: 20, width: 300, height: 60))
label?.textAlignment = .Center
self.view.addSubview(label!)
let tap = UITapGestureRecognizer(target: self, action: "tapAction:")
// 需要点击的次数
tap.numberOfTapsRequired = 2
// 需要触摸的手指数
tap.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tapAction(tapGestureRecognizer: UITapGestureRecognizer) {
self.label?.text = "点击手势"
}
}
运行程序
2. UITapGestureRecognizer详解
我们查看UITapGestureRecognizer的定义:
@available(iOS 3.2, *)
public class UITapGestureRecognizer : UIGestureRecognizer {
// 需要点击的数目, 默认值是1
public var numberOfTapsRequired: Int
// 指定手指数, 默认值是1
public var numberOfTouchesRequired: Int
}
这个类的属性还是蛮少的
3. UITapGestureRecognizer的坑
默认情况下,如果同时设置了单击和双击, 那么双击时,单击也会触发,要解决这个问题,我们要使用requireGestureRecognizerToFail方法, 它是UIGestureRecognizer的方法. 代码在第四部分中展示
4. 完整代码
import UIKit
class ViewController: UIViewController {
var label: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
label = UILabel(frame: CGRect(x: 20, y: 20, width: 300, height: 60))
label?.textAlignment = .Center
self.view.addSubview(label!)
let tap = UITapGestureRecognizer(target: self, action: "tapAction:")
// 需要点击的次数
tap.numberOfTapsRequired = 2
// 需要触摸的手指数
tap.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(tap)
let tapSingle = UITapGestureRecognizer(target: self, action: "tapAction2:")
// 需要点击的次数
tapSingle.numberOfTapsRequired = 1
// 需要触摸的手指数
tapSingle.numberOfTouchesRequired = 2
tapSingle.requireGestureRecognizerToFail(tap)
self.view.addGestureRecognizer(tapSingle)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tapAction(tapGestureRecognizer: UITapGestureRecognizer) {
self.label?.text = "点击手势"
print("双击")
}
func tapAction2(tapGestureRecognizer: UITapGestureRecognizer) {
print("单击")
}
}