首页 文章

UIPanGestureRecognizer不起作用

提问于
浏览
-2

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

enter image description here

Main View:

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

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

3 回答

  • 8

    这是答案:

    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

    试试这个:

    whiteView.userInteractionEnabled=true
    
  • 0

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

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

    希望能帮助到你 .

相关问题