2015-12-03 111 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()中的最后一行,左边的滑动不会触发,因为我试图模仿幻灯片导航栏,所以必须先完成此操作;) –