Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
J.Doe Avatar asked Feb 27 '17 10:02

J.Doe


People also ask

How do I add a footer to a table view?

To only have a footer view, you will need to add a prototype cell, that will allow you to add a footer view below the cell. Let's add a footer now, again, we just need to drag a new view onto the table view, but this time place it below the other view.

Can we use tableView in SwiftUI?

In this blog post, I'll introduce the collection view Table in SwiftUI and explain how to leverage this view on iOS 16 to build a multiplatform app. SwiftUI provides several collection views that you can use to assemble other views into dynamic groupings with complex, built-in behaviors.


2 Answers

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
}
like image 86
Krunal Avatar answered Sep 22 '22 07:09

Krunal


//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"
}
like image 24
Asaduzzaman Shuvro Avatar answered Sep 25 '22 07:09

Asaduzzaman Shuvro