Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on click on label go to next page

Tags:

swift

When I created a button earlier it had the ability to be an "action" IBA function..

How can I create the same thing with a label? so when I click the label my app will direct to a new page. (and how can I make it to direct to a new page? would I have to make a totally new view and in some way link it to that)

Please bare in mind, I'm a totally new to swift and have already come along way with my program,but its been pieces from several tutorials and therefor I might have a hard time understanding your answer the first time.

like image 243
Frederic Avatar asked Oct 30 '15 06:10

Frederic


2 Answers

You can use UITapGestureRecognizer for that and below is simple example for you:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
        label.center = CGPointMake(160, 284)
        label.textAlignment = NSTextAlignment.Center
        label.userInteractionEnabled = true
        label.text = "I'am a test label"
        self.view.addSubview(label)

        let gestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
        label.addGestureRecognizer(gestureRecognizer)
    }

    func handleTap(gestureRecognizer: UIGestureRecognizer) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("next")
        self.presentViewController(vc, animated: true, completion: nil)
    }
}

Result:

enter image description here

Project sample for more Info.

like image 117
Dharmesh Kheni Avatar answered Oct 07 '22 19:10

Dharmesh Kheni


Swift 3

1- Make sure you've checked the "User Interaction Enabled" in attributes inspector.

2- Code:

       let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourVC.labelTapped))
       yourLabel.addGestureRecognizer(gestureRecognizer)

3- Use the func:

    func labelTapped() {
    print("labelTapped tapped")
}
like image 35
Oubaida AlQuraan Avatar answered Oct 07 '22 20:10

Oubaida AlQuraan