添加滑动手势识别器到uilabel(swift)

时间:2016-08-09 03:43:58

标签: swift uigesturerecognizer

        let urgencyLabel = UILabel(frame:CGRectMake(renderWidth,0,80,60))
        urgencyLabel.text = "Urgency"
        view.addSubview(urgencyLabel)

如何向uilabel添加滑动左手势识别器而不是整个视图控制器?

3 个答案:

答案 0 :(得分:0)

您可以在viewController的viewDidLoad方法中创建滑动手势:

override func viewDidLoad(){
    super.viewDidLoad()
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipedToLeft))
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left

    urgencyLabel.addGestureRecognizer(swipeLeft)
}

//Implement the action for the gesture

func swipedToLeft() {
    //Do stuff when swiping left is recognised
}

此外,您还可以在Storyboard / xib中添加手势识别器。请按照本教程获取更多信息 -

https://www.raywenderlich.com/76020/using-uigesturerecognizer-with-swift-tutorial

答案 1 :(得分:0)

以下是一种可能的解决方案:

class ViewController: UIViewController {

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

    let urgencyLabel = UILabel(frame:CGRectMake(100,100,80,60))
    urgencyLabel.text = "Urgency"
    view.addSubview(urgencyLabel)
    urgencyLabel.userInteractionEnabled = true


    let myRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeLeftFunc:")
    myRecognizer.direction = [.Left]

    urgencyLabel.addGestureRecognizer(myRecognizer)

}



func swipeLeftFunc(sender: UISwipeGestureRecognizer) {

        print("Swipe left")

}

使用以下方法启用用户交互非常重要:

urgencyLabel.userInteractionEnabled = true

答案 2 :(得分:0)

试试这个

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipedLeft))
    swipeLeft.direction = .Left
    self.view.addGestureRecognizer(swipeLeft)

}
func swipedLeft()
{
    print("swiped left")
}