UIPanGestureRecognizer 不起作用

UIPanGestureRecognizer does not work

这很奇怪,但是当我向视图添加 UIPanGestureRecognizer 时它不起作用。我的观点是,白色视图是红色视图的子视图:

主视图:

@IBOutlet weak var redView: UIView!
@IBOutlet weak var whiteView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
    whiteView.gestureRecognizers = [panRecognizer]        
}


func handlePan(recognizer:UIPanGestureRecognizer)  {
    //foo
}

当我点击并拖动白色视图时,它不会移动。

如果您使用 swift 语言作为方法,则不能使用 []

var PanGesture = UIPanGestureRecognizer(target: self, action: "respondToPanGesture:")
whiteView.addGestureRecognizer(PanGesture)

希望对您有所帮助。

试试这个:

whiteView.userInteractionEnabled=true

答案如下:

class ViewController: UIViewController {

    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var whiteView: UIView!

    var lastLocation:CGPoint = CGPointMake(0, 0)


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
        whiteView.addGestureRecognizer(panRecognizer)

    }


    func handlePan(recognizer:UIPanGestureRecognizer)  {
        let translation  = recognizer.translationInView(redView)
        whiteView.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // Promote the touched view
        lastLocation = whiteView.center

    }
}

来自 Apple 的文档:

如果您的平移手势识别器 的代码未被调用,请检查以下条件 是否成立,并进行更正根据需要:

视图 isUserInteractionEnabled 属性 设置为 true。图像视图和标签默认将此 属性 设置为 false。

触摸次数介于minimumNumberOfTouchesmaximumNumberOfTouches属性中指定的值之间.

对于 UIScreenEdgePanGestureRecognizer 对象,边缘 属性 已配置并且触摸从适当的边缘开始。

Handling Pan Gestures