J.Doe
J.Doe

Reputation: 725

Set a custom table view footer with Swift

I am trying to set a custom footer to my table view. I created the footer on a nib file and created a controlled for it.

class LoginTableFooter: UITableViewHeaderFooterView

In viewDidLoad() I wrote this code

let footerNib = UINib(nibName: "LoginTableFooter", bundle: nil)
        tableView.register(footerNib, forHeaderFooterViewReuseIdentifier: "LoginTableFooter")

Then I implemented viewForFooterInSection

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let cell = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "LoginTableFooter")
    let header = cell as! LoginTableFooter

    return cell
}

viewForFooterInSection was never called. I also tried to implement viewForHeaderInSection but it was also not called. Do you have an idea what is wrong? I have only one section in my table view; is it possible/better to set the footer directly on viewDidLoad?

Upvotes: 8

Views: 26643

Answers (4)

navin
navin

Reputation: 1

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    footerView.backgroundColor = UIColor.red

    return footerView
  }

Upvotes: 0

Krunal
Krunal

Reputation: 79636

Implement - delegate & datasource for your tableview and set both - heightForFooterInSection & viewForFooterInSection

tableView.delegate = self
tableView.dataSource = self

// set view for footer
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    footerView.backgroundColor = UIColor.blue
    return footerView
}

// set height for footer
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 40
}

Upvotes: 15

user7587085
user7587085

Reputation:

Swift 3 Directly use > viewForFooterInSection

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    footerView.backgroundColor = UIColor.red

    return footerView
  }

Upvotes: 0

Asaduzzaman Shuvro
Asaduzzaman Shuvro

Reputation: 180

//firstly you need to call the delegate and datasource of table view. i.e:

  tableView.delegate = self
  tableView.dataSource = self

//you need to call this delegate

     func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
      return "your expected footer height"
}

Upvotes: 1

Related Questions