What is the cleanest way to add footer view to tableView?

Viewed 54

I would like to know, what is the cleanest and easiest way to add footer to tableview?

Now I do a hardcoding:

func tableView(_ tableView: UITableView,
               viewForFooterInSection section: Int) -> UIView? {
    if viewModel.shouldShowPremiumBanner {
        let footerView: LibraryFooterView = tableView.dequeueReusableHeaderFooter()
        footerView.viewModel = LibraryFooterViewModel(navigator: Locator.navigator,
                                                      localStorage: Locator.localStorage)
        self.tableView.tableFooterView = footerView
        return footerView
    }
    return nil
}


func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    if viewModel.shouldShowPremiumBanner {
        return estimatedSectionFooterHeight
    }
    return .leastNormalMagnitude
}
1 Answers

i would like to add this to tableview not in section

you are already doing it by setting self.tableView.tableFooterView = footerView

as per docs

Use this property to specify a footer view for your entire table. The footer view is the last item to appear in the table's view's scrolling content, and it is separate from the footer views you add to individual sections. The default value of this property is nil.

link : https://developer.apple.com/documentation/uikit/uitableview/1614976-tablefooterview

So simply remove your viewForFooterInSection code and viewDidLoad of your viewController simply set

override func viewDidLoad() {
    super.viewDidLoad()
    let footerView: LibraryFooterView = tableView.dequeueReusableHeaderFooter()
    footerView.viewModel = LibraryFooterViewModel(navigator: Locator.navigator,
                                                  localStorage: Locator.localStorage)
    self.tableView.tableFooterView = footerView
}

By writing self.tableView.tableFooterView = footerView in viewForFooterInSection you are simply resetting the same variable agin and again with no actual visual change, and you are simply wasting CPU cycles by creating view and its viewModel again and again. Set it once may be in viewDidLoad or wherever it makes sense in your case and just leave it.

Hope it helps

Related