Swift : 将 UIPanGestureRecognizer 设置为 UIView

Swift : Set UIPanGestureRecognizer to UIView

我正在尝试为特定的 UIView 设置 UIPanGestureRecognizer

    self.halfViewBlue.frame = CGRectMake(0, 0, self.bounds.width / 2, self.bounds.height)
    self.halfViewBlue.backgroundColor = UIColor.blueColor()
    halfViewBlue.alpha = 1.0
    self.addSubview(self.halfViewBlue)

    self.halfViewRed.frame = CGRectMake(self.frame.midX, 0, self.bounds.width / 2, self.bounds.height)
    self.halfViewRed.backgroundColor = UIColor.redColor()
    halfViewRed.alpha = 1.0
    self.addSubview(self.halfViewRed)

    //Pan Gesture for Red
    let panGestureRed = UIPanGestureRecognizer()
    panGestureRed.addTarget(self, action: "handlePanRed:")
    self.addGestureRecognizer(panGestureRed)
    self.userInteractionEnabled = true

    //Pan Gesture for Blue
    let panGestureBlue = UIPanGestureRecognizer()
    panGestureBlue.addTarget(self, action: "handlePanBlue:")
    self.addGestureRecognizer(panGestureBlue)
    self.userInteractionEnabled = true

}

func handlePanRed(gesture : UIPanGestureRecognizer){

    if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){

        let velocity : CGPoint = gesture.velocityInView(halfViewRed)

        //Pan Down
        if(velocity.y > 0){
            print("Panning down")
            hideRedBar()
            produceBlueBar()
        }
        //Pan Up
        if(velocity.y < 0){
            print("panning up")
            hideBlueBar()
            produceRedBar()
        }
    }
}


func handlePanBlue(gesture : UIPanGestureRecognizer){

    if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){

        let velocity : CGPoint = gesture.velocityInView(halfViewBlue)

        //Pan Down
        if(velocity.y > 0){
            print("Panning down")
            hideBlueBar()
            produceRedBar()
                        }

        if(velocity.y < 0){
            print("panning up")
            hideRedBar()
            produceBlueBar()

        }
    }
}

这里我简单地创建了两个 UIView,它们都在屏幕上垂直分割(平均)。 然后我添加了两个 panGestures 和一个函数来跟随它。我的问题是,唯一被识别的 panGesture 是 "panGestureBlue",奇怪的是我可以在屏幕的任何部分控制它,而不仅仅是 "halfViewBlue" 所在的那一半。 所以我假设这两个 panGestures 都被添加到 self.view 而不是它应该放在一起的 UIView,并且正在读入 "panGestureBlue" 因为它是在 "panGestureRed" 之后添加的.我试着把 "halfViewBlue" 放在 "panGestureBlue.addTarget" 中,而不是 "self",但它崩溃了。

我该如何解决这个问题!?

您应该在子视图而不是父视图上添加平移手势,如下所示:

self.halfViewRed.addGestureRecognizer(panGestureRed)
self.halfViewBlue.addGestureRecognizer(panGestureBlue)