2016-04-16 43 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