Home > OS >  delegate from VC to TableViewCell to update cell
delegate from VC to TableViewCell to update cell

Time:01-20

I'm trying to update all my cell from my VC with delegate.

it works from cell to update something on VC, but when I try to update something from VC to make changes on cell, it doesn't work.

In my VC I added :

protocol MainViewDelegate {
    func updateValueInCell()
}
var delegate: MainViewDelegate?
@IBAction func modifyValueAtVC(_ sender: Any) {
    func updateValueInCell()
}

and in my cell

var mainView = ViewController()

extension CustomTableViewCell : MainViewDelegate {
    func updateValueInCell() {
        print("hello")
    }

 override func awakeFromNib() {
        super.awakeFromNib()
        mainView.delegate = self
    }

but nothing happened when I pressed my button from my View Controller.

is it the correct way on update cell from VC or do you guys have any other ideas?

thank you! :)

CodePudding user response:

vc update cell only need reloadData, if u want cell trigger viewcontroller by cell, use delegate.

class MainView:UIViewController,CustomTableViewCellDelegate{
    @IBOutlet weak var table: UITableView!//table.delegate = self
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DailyScheduleTableViewCell
        cell.delegate = self
        //update what you want
        return cell
    }

    func onClick(cell: CustomTableViewCell) {
        //cell click trigger
    }

    @IBAction func modifyValueAtVC(_ sender: Any) {
        table.reloadData()
    }
}

protocol CustomTableViewCellDelegate{
    func onClick(cell:CustomTableViewCell)
}

class CustomTableViewCell:UITableViewCell{
    var delegate:CustomTableViewCellDelegate!

    @IBAction func onClick(_ sender: Any) {
        del?.onClick(cell: self)
    }

}
  •  Tags:  
  • Related