UIPanGestureRecognizer不起作用

时间:2016-04-16 08:49:19

标签: swift uigesturerecognizer uipangesturerecognizer

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

enter image description here

主要观点:

@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
}

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

4 个答案:

答案 0 :(得分:8)

试试这个:

whiteView.userInteractionEnabled=true

答案 1 :(得分:0)

以下是答案:

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

    }
}

答案 2 :(得分:0)

摘自Apple文档:

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

视图 isUserInteractionEnabled 属性设置为true 。图片视图和标签默认情况下将此属性设置为false。

触摸次数 minimumNumberOfTouches maximumNumberOfTouches 属性中指定的值之间。

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

Handling Pan Gestures

答案 3 :(得分:-2)

如果您使用swift语言方法,则无法使用[]

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

希望它有所帮助。