Search code examples
iosswiftuitableviewtablefooterview

UITableViewCell doesn't recognise action of button when implemented as a FooterView for the UITableView, with multiple footer views


I am trying to add a footerView to each individual section in my app. I've successfully added the header since it doesn't require to have any button, however when I try to use the same implementation to my footerView, where there must be a button that correctly identifies the section from where it was tapped, it doesn't work. I am adding both the header and the footer view as prototype cells from my UITableView. The footerView subclasses UITableViewCell and I added the button in interface builder, even a simple print statement cannot be run down.

How could my footerView recognise that I am pressing the button and also, how can it recognise the section from where it was pressed?

import UIKit

class FooterTableViewCell: UITableViewCell {


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }

    var footerDelegate:FooterTableViewCellDelegate?

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }



    @IBAction func addSetIsPressed(_ sender: UIButton) {

        print("Add Set is pressed")
        footerDelegate?.didAddSetIsPressed(cell:self)
    }


}

protocol FooterTableViewCellDelegate {

    func didAddSetIsPressed(cell:FooterTableViewCell)
}

There is my implementation of my Footertableviewcell

As you can see, I didn't use any nib files or added the footer programatically, I used another tableViewCell and I use its view.contents to show it in the tableview

As you can see, I didn't use any nib files or added the footer programatically, I used another tableViewCell and I use its view.contents to show it in the tableview

Here I implement the rest of the code in my TableView controller

class TableViewController: UITableViewController, ExerciseTableViewCellDelegate, UICollectionViewDelegate, UICollectionViewDataSource, FooterTableViewCellDelegate {


    func didAddSetIsPressed(cell: FooterTableViewCell) {

        print("Add set is pressed from delegate")
    }

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

    let cell = tableView.dequeueReusableCell(withIdentifier: "footerCell") as! FooterTableViewCell
    cell.footerDelegate = self

    return cell.contentView
}

Thanks in advance for the help


Solution

  • A better approach might be to use a closure / callback, but to explain what's happening...

    With this line:

    return cell.contentView
    

    you are returning the cell's view. The code from the cell class goes away, as cell goes out-of-scope at that point.

    Try returning the cell itself:

    return cell
    

    and see if you have better luck.