johnniexo88
johnniexo88

Reputation: 313

Get label from cell - swift

Here is my code:

var username: String!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

    username = usernameLabel.text
    cell.button.userInteractionEnabled = true
    let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
    cell.button.addGestureRecognizer(tapButton)

    return cell as MainCell
}

func tapButton(sender:UITapGestureRecognizer) {
    print(username) //this prints the wrong cell... why?
}

i want to be able to print the variable username but it prints the wrong username for the cell when i press on the button. why is that and how can i fix it?

Upvotes: 1

Views: 1364

Answers (4)

Farhad Faramarzi
Farhad Faramarzi

Reputation: 465

you should implement action button in MainCell . you have available with username and this is best practice ;)

class MainCell: UITableViewCell {
   @IBOutlet weak var usernameLabel: UITextView!

   func tabButton(sender: AnyObject) {
       print(usernameLabel.text)
   } 
}

Upvotes: 1

Moin Shirazi
Moin Shirazi

Reputation: 4425

1) In your cellForRowAtIndexPath: method, assign button tag as index:

cell.yourbutton.tag = indexPath.row;

2) Add target and action for your button as below:

cell.yourbutton.addTarget(self, action: #selector(self.yourButtonClicked), forControlEvents: .TouchUpInside)

3) Code actions based on index as below in ViewControler:

func yourButtonClicked(sender: UIButton) {
    if sender.tag == 0 {
        // Your code here

    }
}

Ref SO: https://stackoverflow.com/a/20655223/4033273

Upvotes: 0

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

add tag in cellForRowAtIndex

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

     cell.button.userInteractionEnabled = true
    cell.button.setTitle( usernameLabel.text, forState: .Normal)
     cell.button.tag = indexPath.row
     cell.button.addTarget(self, action: #selector(ViewController.tapButton(_:)), forControlEvents: .TouchUpInside)

    return cell as MainCell
}

get action as

func tapButton(sender: UIButton!) 
{
   username =  sender.titleLabel.text
    print(username)  
}

Upvotes: 1

Anupam Mishra
Anupam Mishra

Reputation: 3588

It will print the latest value stored in username because every indexPath of cell, it will update the value in username & at the end will give you the latest updated value no matter which cell you are tapping

Upvotes: 0

Related Questions