一.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)
}
}
未完。。。。。
博客介绍了UIGestureRecognizer手势,包括拖动、捏合、旋转等多种类型。还讲述了为view添加点击事件的步骤,如创建view、点击方法并添加事件。此外,提到了轻扫事件,创建新view并设置长按事件,最后给出了部分代码示例。
177

被折叠的 条评论
为什么被折叠?



