iOS手勢處理由UIGestureRecognizer控制,不同手勢有這個(gè)類的不同子類處理,不同手勢處理有不同的相關(guān)屬性。
| 子類 | 描述 |
|---|---|
| UITapGestureRecognizer | 點(diǎn)擊手勢 |
| UIPanGestureRecognizer | 跟著手移動(dòng)手勢 |
| UIPinchGestureRecognizer | 縮放手勢 |
| UIRotationGestureRecognizer | 旋轉(zhuǎn)手勢 |
| UISwipeGestureRecognizer | 輕掃手勢 |
| UILongPressGestureRecognizer | 長按手勢 |
| UIScreenEdgePanGestureRecognizer | 屏幕邊緣滑動(dòng)手勢 |
手勢處理的步驟一般:
- 初始化手勢,并添加到需要手勢的View中
- 添加手勢回調(diào)方法
UITapGestureRecognizer
屬性numberOfTapsRequired表示點(diǎn)擊次數(shù),屬性numberOfTouchesRequired表示點(diǎn)擊手指數(shù)。
var isChange = false
...
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(tap:)))
tap.numberOfTapsRequired = 2
...
imageView.addGestureRecognizer(tap)
...
@objc func tap(tap: UITapGestureRecognizer) {
let center = imageView.center
if isChange {
imageView.frame.size.width /= 2
imageView.frame.size.height /= 2
imageView.center = center
isChange = false
} else {
imageView.frame.size.width *= 2
imageView.frame.size.height *= 2
imageView.center = center
isChange = true
}
}
UIPanGestureRecognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pan(pan:)))
@objc func pan(pan: UIPanGestureRecognizer) {
if pan.state == .began || pan.state == .changed {
// 移動(dòng)后的變化(變化值類似向量)
let translation = pan.translation(in: imageView.superview)
print(translation)
imageView.center = CGPoint(x: imageView.center.x + translation.x, y: imageView.center.y + translation.y)
// view移動(dòng)后,把上一步的移動(dòng)值變?yōu)?,否則移動(dòng)值為遞增
pan.setTranslation(CGPoint.zero, in: imageView.superview)
}
}
UIRotationGestureRecognizer
let rotation = UIRotationGestureRecognizer(target: self, action: #selector(ViewController.rotation(rotation:)))
@objc func rotation(rotation: UIRotationGestureRecognizer) {
if rotation.state == .began || rotation.state == .changed {
imageView.transform = CGAffineTransform(rotationAngle: rotation.rotation)
}
}
UISwipeGestureRecognizer
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipe(swipe:)))
swipe.direction = .up
swipe.numberOfTouchesRequired = 3
@objc func swipe(swipe: UISwipeGestureRecognizer) {
print("掃的方向:\(swipe.direction),掃的手指數(shù):\(swipe.numberOfTouchesRequired)")
}
UILongPressGestureRecognizer
numberOfTouchesRequired 長按的指頭數(shù)
minimumPressDuratio 長按最小時(shí)間(秒)
let long = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.long(long:)))
long.numberOfTouchesRequired = 2
long.minimumPressDuration = 1
@objc func long(long: UILongPressGestureRecognizer) {
print("長按手勢,長按字頭數(shù)為\(long.numberOfTouchesRequired)")
}
UIScreenEdgePanGestureRecognizer
let screenEdge = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(ViewController.screenEdage(screenEdage:)))
screenEdge.edges = .left
@objc func screenEdage(screenEdage: UIScreenEdgePanGestureRecognizer) {
print("屏幕邊緣滑動(dòng)手勢:\(screenEdage.edges)")
}
詳細(xì)代碼: GestureDemo