使用PanGestureRecognizer创建UIView并在不抬起手指的情况下激活它

时间:2015-09-28 01:32:27

标签: ios iphone swift uiview uigesturerecognizer

我在touchesBegan()时在手指的位置创建了一个UIView,在屏幕上创建了一个圆圈:

在ViewController中:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {

        let pos = touch.locationInView(view)

        let radius: CGFloat = touch.majorRadius * 2
        let circleView = CircleView(frame: CGRectMake(pos.x - radius / 2, pos.y - radius / 2, radius, radius))
        view.addSubview(circleView)

    }
}

在CircleView中:

override init(frame: CGRect) {
    super.init(frame: frame)

    let recognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:"))
    recognizer.delegate = self
    self.addGestureRecognizer(recognizer)

}

这会创建圆圈,但在我移动手指时不会立即移动圆圈。相反,我必须先拿起我的手指,然后在handlePan()开始之前将其放回圆圈。

有没有办法开始跟踪平移手势而不抬起产生它的父视图的手指,考虑到可能有多个手指触摸并在屏幕上移动?

3 个答案:

答案 0 :(得分:2)

这里的问题是你使用touchesBegan和UIPanGestureRecognizer。为获得最佳效果,请使用其中一种。如果您打算只使用平移手势(这就是我要做的),请执行以下操作:

func handlePan(gesture: UIPanGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.Began {
        //handle creating circle
    } else if gesture.state == UIGestureRecognizerState.Changed {
        //handle movement
    }
}

希望这有帮助!

答案 1 :(得分:1)

如果您已在方法touchesBegan:withEvent:

中成功创建了圆圈视图

你可以

  1. 将该圈子视为属性

  2. 直接在方法touchesMoved:withEvent:

  3. 中移动该圆圈视图

    这不会要求你先拿起手指

答案 2 :(得分:0)

我能够通过保存所有活动触摸的字典并在touchesBegan()中创建圆形视图并通过查询该字典来更新它们在touchesMoved()中的位置来完成多个独立触摸。

var fingerTouches = [UITouch: CircleView]()

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {

        let pos = touch.locationInView(view)

        let radius: CGFloat = touch.majorRadius * 2
        let circle = CircleView(frame: CGRectMake(pos.x - radius / 2, pos.y - radius / 2, radius, radius))
        view.addSubview(circle)

        fingerTouches[touch] = circle

    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {

        let pos = touch.locationInView(view)

        let radius: CGFloat = touch.majorRadius * 2
        fingerTouches[touch]!.frame = CGRectMake(pos.x - radius / 2, pos.y - radius / 2, radius, radius)

    }

}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {
        fingerTouches[touch]!.removeFromSuperview()
    }
}