一.UIGestureRecognizer手势
1.UIPanGestureRecognizer(拖动)
2.UIPinchGestureRecognizer(捏合)
3.UIRotationGestureRecognizer(旋转)
4.UITapGestureRecognizer(点按)
5.UILongPressGestureRecognizer(长按)
6.UISwipeGestureRecognizer(轻扫)
二.为view添加点击事件
1、创建一个view
首先我们随便创建一个view 并添加外边框。
let touchView = UIView(frame: CGRect(x: 30, y: 50, width: 170, height: 130))
touchView.tag = 1
touchView.layer.borderWidth = 1
// 开始交互
touchView.isUserInteractionEnabled = true
2、创建一个点击事件
创建一个点击方法
(注意:方法前面要加@objc)
@objc func touch(_ gesture: UIGestureRecognizer) {
let view = gesture.view
print(view?.tag)
}
给view添加点击事件
let touch = UITapGestureRecognizer(target: self, action: #selector(self.touch(_:)))
touchView.addGestureRecognizer(touch)
运行,点击view会打印 view的tag
三、轻扫事件
同样创建一个新的view
let longPressView = UIView(frame: CGRect(x: 100, y: 250, width: 200, height: 130))
longPressView.layer.borderWidth = 1
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressAction(_:)))
longPressView.addGestureRecognizer(longPress)
长按的事件
@objc func longPressAction(_ gesture: UIGestureRecognizer) {
print(11)
}
当我们一直按住view区域,会持续打印11
全部代码:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let touchView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 130))
touchView.tag = 1
touchView.layer.borderWidth = 1
touchView.isUserInteractionEnabled = true
let touch = UITapGestureRecognizer(target: self, action: #selector(self.touch(_:)))
touchView.addGestureRecognizer(touch)
let longPressView = UIView(frame: CGRect(x: 100, y: 250, width: 200, height: 130))
longPressView.layer.borderWidth = 1
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressAction(_:)))
longPressView.addGestureRecognizer(longPress)
self.view.addSubview(longPressView)
self.view.addSubview(touchView)
}
@objc func longPressAction(_ gesture: UIGestureRecognizer) {
print(11)
}
@objc func touch(_ gesture: UIGestureRecognizer) {
let view = gesture.view
print(view?.tag)
}
}
未完。。。。。