2016-04-16 40 views
-3

这很奇怪,但是当我将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 
} 

当我点击并拖动白色的观点也不会移动。

+0

这是一个PangestureRecognizer,不TapgestureRecognizer ??? – Khuong

+1

这是什么问题?您已将手势识别器分配给白色视图。 – t0mm13b

+0

@ t0mm13b,我无法移动白色视图,这是问题所在。 – Maysam

回答

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

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

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

希望它有帮助。

+0

这不是问题 – Maysam

5

试试这个:

whiteView.userInteractionEnabled=true