mefahimrahman
mefahimrahman

Reputation: 349

How to pass data from nested Tableview cell to UIViewController

I've a tableview (T) in a ViewController (V). In that tableview, I've a custom cell (C) what has a stackview and depending on the data it adds another two custom cell (c1 & c2) in its stack view.

In c1 and c2 I've two buttons and IBAction outlets for these buttons. Now as here I've this nested situation, how can I catch the click event on a button of c1 or c2 from viewcontroller V?

I've created and confirmed a delegate in Custom Table View Cell (C) and now calling the delegate from the IBAction outlets of c1 and c2.

@IBAction func buttonInC1Cell(_ sender: Any) {
    delegate?.c1ButtonClicked()
}

@IBAction func buttonInC2Cell(_ sender: Any) {
    delegate?.c2ButtonClicked()
}

But as I've not any table view in custom table view C, I can not able to retreive the clicked cell index there.

Upvotes: 0

Views: 152

Answers (1)

Zoro4rk
Zoro4rk

Reputation: 111

You can pass model of data source into cell and pass it via callback(delegates).

class YourCell: UITableViewCell {
    private var model: YourModel = .init()

    func setData(model: YourModel) {
       self.model = model
       // Change UI with model data
    }

    @IBAction func buttonInC1Cell(_ sender: Any) {
       delegate?.c1ButtonClicked(self.model)
    } 

    @IBAction func buttonInC21Cell(_ sender: Any) {
       delegate?.c2ButtonClicked(self.model)
    }
}

Upvotes: 0

Related Questions