2015-12-03 112 views
0

我的工作代碼將一個標籤滑動到窗口左側,並再次向右滑動以完全顯示它。由於我正在迅速學習,我希望你的意見能夠改進。我包括了一些失敗的保理。一個視圖上的多個手勢識別器

工作代碼:

import UIKit 

class ViewController: UIViewController { 

@IBOutlet weak var myLabel: UILabel! 
@IBOutlet var parentView: UIView! 
var swipGestureRight: UISwipeGestureRecognizer! 
var swipGestureLeft: UISwipeGestureRecognizer! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    myLabel.userInteractionEnabled = true 

    swipGestureLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipViewLeft:")) 
    swipGestureLeft.direction = .Left 
    parentView.gestureRecognizers = [swipGestureLeft] 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func swipViewLeft(gesture: UISwipeGestureRecognizer){ 
    UIView.animateWithDuration(0.3, animations: {self.myLabel.center.x -= (self.myLabel.bounds.width)}, completion: nil) 
    swipGestureRight = UISwipeGestureRecognizer(target: self, action: Selector("swipViewRight:")) 
    swipGestureRight.direction = .Right 
    parentView.gestureRecognizers = [swipGestureRight] 
} 

func swipViewRight(gesture: UISwipeGestureRecognizer){ 
    UIView.animateWithDuration(0.3, animations: {self.myLabel.center.x += (self.myLabel.bounds.width)}, completion: nil) 
    swipGestureLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipViewLeft:")) 
    swipGestureLeft.direction = .Left 
    parentView.gestureRecognizers = [swipGestureLeft] 
} 
} 

試圖改善後失敗:

import UIKit 
class ViewController: UIViewController { 

@IBOutlet weak var myLabel: UILabel! 
@IBOutlet var parentView: UIView! 
var swipGestureRecognizer: UISwipeGestureRecognizer! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    myLabel.userInteractionEnabled = true 

    swipGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipping:")) 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func swipping(gestureRecognizer: UISwipeGestureRecognizer){ 
    if gestureRecognizer.direction == .Left { 
     parentView.gestureRecognizers = [gestureRecognizer] 
     UIView.animateWithDuration(0.3, animations: {self.myLabel.center.x -= (self.myLabel.bounds.width)}, completion: nil) 
    } else { 
     UIView.animateWithDuration(0.3, animations: {self.myLabel.center.x += (self.myLabel.bounds.width)}, completion: nil) 
    } 
} 
} 

回答

0

如何移動

parentView.gestureRecognizers = [gestureRecognizer] 

viewDidLoad()

+0

如果我將它移動到viewDidLoad()中的最後一行,左邊的滑動不會觸發,因爲我試圖模仿幻燈片導航欄,所以必須先完成此操作;) –