Sajjad Aims Sajjad Aims - 2 months ago 12
Swift Question

View tableview cell text on table view cell button

I have a table view where I have created a label and two buttons. I am stuck while getting the text from the label on button click. I have created an array list like:

let arrayList: [String] = [ "aaa" , "bbb" , "ccc"]


I want if I click the button on
index[0]
I shall get "aaa" and if
index[2]
I shall get "ccc"

enter image description here

@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var infoButton: UIButton!

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked", forControlEvents: .TouchUpInside)

Answer

you need to do like

swift3

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: #selector(yourVCName.buttonClicked(_:)), for: .touchUpInside)

get action as

 @IBAction func buttonClicked(_ sender: UIButton){

     print(self.arrayList[sender. tag])

}

Swift2

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)


@IBAction func buttonClicked(sender: UIButton){

     print(self.arrayList[sender. tag])

}