ios – 以编程方式在Swift中启动手势识别器?

我试图确定是否有一种以编程方式设置手势识别器状态的方法,强制它在实际检测到用户输入之前开始.

例如,我在检测到长按时向图像添加平移手势识别器,就像这样;

let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
myImage.addGestureRecognizer(longPressRecognizer)

func longPressed(sender: UILongPressGestureRecognizer) {

   let mainWidth = UIScreen.mainScreen().bounds.width
   let mainHeight = UIScreen.mainScreen().bounds.height

   let myView: UIView(frame: CGRect(x: 0, y: 0, width: mainWidth, height: mainHeight)

   let gestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
   myView.addGestureRecognizer(gestureRecognizer)

   self.view.addSubview(myView)

}

在handlePan()函数中,我能够确定平移的开始和结束时间;

func handlePan(gesture: UIPanGestureRecognizer) {

    if gesture!.state == UIGestureRecognizerState.Began {
        print("Started pan")
    }

    if gesture!.state == UIGestureRecognizerState.Ended {
        print("Ended pan")
    }

}

我的问题是,为了检测手势何时开始,用户必须(1)长按图像,(2)松开手指,(3)按住并开始平移.理想情况下,我想让用户(1)长按图像,(2)开始平移.

为了做到这一点,我想象我需要找出一种方法来“欺骗”事物,使人们相信平移手势已经开始了.

注意:实际上,比这里提供的更复杂,这就是为什么我需要使用平移手势添加子视图,而不是直接将平移手势添加到图像.

最佳答案 您要做的是在前面添加手势识别,将他们的代表设置为您的类,允许他们同时识别(使用以下方法),并且仅在成功识别长按时使用来自平移的数据.

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
    shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
} 
点赞