Ad

Why Does It Return Only One Uid When Tapping A Button Inside The TableViewCell?

My problem that I present to you is that, I have a button inside a table View Cell and when tapped a person name it displays the current user uid but the things is, when I tap a different person name it should return that user uid not the current one, Can you please help me fix this bug Thank you in advance, feel free to ask for more code is you don't fully understand my code

func numberOfSections(in tableView: UITableView) -> Int {

    return array.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}     




 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


     //This is a button inside the tableView cell
    cell.buttonName.setTitle(array[indexPath.section].uid ,for: .normal)
    //this is putting the name inside another ViewController label and display its name 
    self.secondViewController.name.text = array[indexPath.section].uid
 cell.buttonName.addTarget(self, action: #selector(addName), for: .touchUpInside) 
 }
   let person = secondViewController()


@objc func addName() {

    person.name.text = array[?].uid
    profiler.hidesBottomBarWhenPushed = true


}
Ad

Answer

You need to write a method that makes the action that you need, and add this action to the button

func updatePersonName(_ button:UIButton) {
    self.secondViewController.name.text = button.titleLabel.text
}     

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


     //This is a button inside the tableView cell
    cell.buttonName.setTitle(array[indexPath.section].uid ,for: .normal)
    //We remove all actions added to this button (reuse)
    cell.buttonName.removeTarget(self, action: nil, for: .allEvents)
    //Add new target
    cell.buttonName.addTarget(self, action:#selector(updatePersonName), for: .touchUpInside)

    return cell
 }
Ad
source: stackoverflow.com
Ad