iOS手势识别--上下左右滑动
2018-10-09 本文已影响192人
攞天炽
-
iOS里对view手势的操作。可以通过
UISwipeGestureRecognizer
来进行操作,也可以通过判断点击的偏移距离来进行判断(可能有bug)。 -
下面是使用
UISwipeGestureRecognizer
进行手势操作。首先要允许view可以进行用户交互
view.isUserInteractionEnabled = true
然后初始化UISwipeGestureRecognizer,将手势添加到view上。上下左右都可以。
let recognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(leftPushInfo))
// recognizer.direction = .right // 右滑
// recognizer.direction = .down //下滑
// recognizer.direction = .up //上滑
recognizer.direction = .left //左滑
self.contentView.isUserInteractionEnabled = true
self.contentView.addGestureRecognizer(recognizer)
下面是响应事件。
@objc private func leftPushInfo(){
print("左滑")
}
还有第二种方法,会出现bug的。下面是具体的代码执行
// 当前拖拽地方位移
var m_curPointLoc:CGPoint = CGPoint.zero
// parent view 起始位移
var m_handleParentviewOrginX:Double = 0.0
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
let point:CGPoint! = ((touches as NSSet).anyObject() as AnyObject).location(in: self.view)
if m_curPointLoc.x != 0 && point.x != m_curPointLoc.x {
if point.x > m_curPointLoc.x {
// 右
} else {
// 左
}
}
m_curPointLoc = point
}
会出现滑动多次的现象。不建议使用。