Search code examples
iosswifttableviewswift5

How to print/pass the text of a Button in a tableViewCell to another ViewController in Swift?


I want to print the text of the Button of that particular tableViewCell when it is clicked. And also notice that the click will also dismiss the view. Please help me to solve this issue

The below is the code that I have tried:

extension AlertViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return flags.count
    }
    
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let flag = flags[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "FlagTableViewCell") as! FlagTableViewCell
        cell.setUp(flag: flag)
        //clickedFlagName = cell.flagNameLbl.text!
//        print("Clickeeeeeeeeeeddddddd" + "\(clickedFlagName)")
        clickedFlagName = cell.flagNameBtn.title(for: .normal)!
        print("WhennnnClickeeeeeeeeeeddddddd   " + "\(clickedFlagName)")
        cell.flagNameBtn.addTarget(self, action: #selector(self.clickedFlagAction), for: .touchUpInside)
        
        return cell
    }
    
   
    @objc func clickedFlagAction(_ sender: Any?) {
        print("Tapped")
        dismiss(animated: true)
    }
}
 

enter image description here


Solution

  • Set up your FlagTableViewCell with a button that has no action attached to it, but with an IBOutlet. Let's call it flagCellButton.

    In your tableView(_:cellForRowAt:) method,

    Dequeue a cell and cast it to the FlagTableViewCell type as you are doing now. Then call removeTarget(_:action:for:) on the flagCellButton, passing in nil for target and action, and .touchUpInside as the control event. (This cleans up any actions from a recycled cell.)

    Call cell.flagCellButton.addTarget(_:action:for:) to add an IBAction from your view controller on the cell.

    Set up your IBAction to expect the sender to be of type UIButton. In that IBAction, fetch the title of the sender, and pass that title to the new view controller, then dismiss the current view controller.

    Edit:

    Note that if you set up your app to require iOS >= v 14, you can use the new methods in UIControl that let you attach a UIAction to a button/control instead of a target/action. The advantage of a UIAction is that it takes a closure rather than a selector, so you can provide the code in-line rather than having to define an IBAction method in your view controller. You'd use a similar approach of removing the old `UIAction from the button and adding a new one.