zzheads
zzheads

Reputation: 1472

Update footer in UITableView

Have custom footer view in my UITableView:

public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {   // custom view for footer. will be adjusted to default or specified footer height
    return footer()
}

func footer() -> UILabel {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (navigationController?.navigationBar.bounds.size.height)!))
    label.backgroundColor = AppColors.Bordo.color
    label.font = UIFont.boldSystemFont(ofSize: 16)
    label.textColor = .white
    label.text = "Selected \(self.selectedGenres.count) of \(self.genres.count)"
    label.textAlignment = .center
    return label
}

When user select/deselect row in table view I want refresh my footer with info of selected rows. How I can do it without reloading whole tableview? And what method footerView(forSection: indexPath.section) of UITableView does?

Upvotes: 0

Views: 1631

Answers (2)

zzheads
zzheads

Reputation: 1472

Done it using Rajesh Choudhary proposal and computing property:

var selectedGenres: [Genre] = [] {
    didSet {
        self.footerForTableView.text = titleForFooter
    }
}

var titleForFooter: String {
    return "Selected \(self.selectedGenres.count) of \(self.genres.count)"
}

lazy var footerForTableView: UILabel = {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (self.navigationController?.navigationBar.bounds.size.height)!))
    label.backgroundColor = AppColors.Bordo.color
    label.font = UIFont.boldSystemFont(ofSize: 16)
    label.textColor = .white
    label.text = self.titleForFooter
    label.textAlignment = .center
    return label
}()

Upvotes: 0

Rajesh Choudhary
Rajesh Choudhary

Reputation: 1340

create a global object of label... and init it only when the label is nil... and you can access this label anywhere in code.

let globalLabel : UILabel ?

public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {   // custom view for footer. will be adjusted to default or specified footer height
    return footer()
}

func footer() -> UILabel {

    if (globalLabel == nil) {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (navigationController?.navigationBar.bounds.size.height)!))
        label.backgroundColor = AppColors.Bordo.color
        label.font = UIFont.boldSystemFont(ofSize: 16)
        label.textColor = .white
        label.textAlignment = .center
        globalLabel = label
    }

    globalLabel.text = "Selected \(self.selectedGenres.count) of \(self.genres.count)"

    return globalLabel
}

Upvotes: 1

Related Questions