swift

iOS手势识别--上下左右滑动

2018-10-09  本文已影响192人  攞天炽

然后初始化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
    }

会出现滑动多次的现象。不建议使用。

上一篇 下一篇

猜你喜欢

热点阅读