在UITableView中更新页脚

时间:2016-12-13 10:08:56

标签: swift uitableview

在我的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
}

当用户在表视图中选择/取消选择行时,我想要使用所选行的信息刷新我的页脚。如何在不重新加载整个tableview的情况下完成它? UITableView的footerView(forSection:indexPath.section)有什么方法呢?

2 个答案:

答案 0 :(得分:1)

创建一个标签的全局对象...并仅在标签为nil时启动它...并且您可以在代码中的任何位置访问此标签。

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
}

答案 1 :(得分:0)

使用Rajesh Choudhary提议和计算属性完成它:

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
}()