Gil
Gil

Reputation: 569

How to present another view controller by tapping on a label inside a tableview cell

I want to create a segue to from an object (label) inside a tableview cell to another view controller.

example: imagine the instagram feed tableview - tapping the number of likes under an image will push a second view with the list of people who liked an image.

How can i do that? I know it's possible when tapping a cell but i need a solution for when tapping a label inside the cell...

thanks!

Upvotes: 0

Views: 4712

Answers (3)

Nurdin
Nurdin

Reputation: 23883

You can use UITapGestureRecognizer.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var lblTxt: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()

        let recognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
        recognizer.numberOfTapsRequired = 1;
        lblTxt.addGestureRecognizer(recognizer)
        lblTxt.userInteractionEnabled = true;
}

func handleTap(recognizer: UITapGestureRecognizer){
        println("tapped!")
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let secondViewController = storyBoard.instantiateViewControllerWithIdentifier("secondView") as SecondViewController
        self.presentViewController(secondViewController, animated:true, completion:nil)
    }

Upvotes: 0

Victor Sigler
Victor Sigler

Reputation: 23451

You have to make the following steps :

  1. Define userInteractionEnabled = true for the label using Interface Builder or in code, as you wish, (VERY IMPORTANT!!) without this the tap is not enabled.
  2. Define an action to the Tap Gesture Recognizer to handle the tap inside the label.
  3. To present the another ViewController you can do one of the following two things :

    • Make a modal segue from the Tap Gesture Recognizer to the another ViewController using the Interface Builder or make an action for the Tap Gesture Recognizer and then present the another ViewController manually using the presentViewController function.

I thought the first is more easy to present the another ViewController, Is up to you.

I hope this help you.

Upvotes: 1

Cihan Tek
Cihan Tek

Reputation: 5409

You can simply use a button and set its title instead of using a label. If you have to use a UILabel for some reason, then you can do so by setting its userInteractionEnabled property to true and then adding a UITapGestureRecognizer to it.

Upvotes: 0

Related Questions