在页脚上显示行数

Arn*_*ues 3 uitableview ios swift

我想对我的应用做一件简单的事情。 在此处输入图片说明

看一下我的主要ViewController:

class Page1: UITableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Shared.instance.employees.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1

        cell.nameLabel.text = Shared.instance.employees[indexPath.row].name
        cell.positionLabel.text = Shared.instance.employees[indexPath.row].position

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? Page2,
            let indexPath = tableView.indexPathForSelectedRow {
            destination.newPage = Shared.instance.employees[indexPath.row]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我添加越来越多的iten时,我必须添加什么功能来显示行数?

有和没有代表之间的区别:

在此处输入图片说明

在此处输入图片说明

vad*_*ian 5

只是实施

override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    return "Total \(Shared.instance.employees.count) rows"
}
Run Code Online (Sandbox Code Playgroud)

如果要自定义标题,则必须实现tableView:viewForFooterInSection:并返回一个视图,例如:

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 30.0))
    label.font = UIFont.boldSystemFont(ofSize: 20.0)
    label.textAlignment = .center
    label.text =  "Total \(Shared.instance.employees.count) rows"
    return label
}
Run Code Online (Sandbox Code Playgroud)

旁注:不要Shared.instance.employees多次调用,而是使用一个临时变量:

let employee = Shared.instance.employees[indexPath.row]
cell.nameLabel.text = employee.name
cell.positionLabel.text = employee.position
Run Code Online (Sandbox Code Playgroud)

  • 不,`tableView:viewForFooterInSection:`是类似于“ tableView:titleForFooterInSection:`”的委托方法。您必须返回一个UIView实例,该视图可以包含您喜欢的任何内容,但您需要负责外观(大小,字体,对齐方式等)。 (2认同)
  • 确实,您已经**选择了一种委托方法,但是,如果实现了`viewForFooterInSection`,则将忽略`titleForFooterInSection`。 (2认同)