Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display number of rows on footer

I want to do a simple thing to my app. enter image description here

Take a look at my main 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]
        }
    }
}

So, what function do I have to add to show the number of rows as I add more and more itens?

Differences between with and without delegates:

enter image description here

enter image description here

like image 415
Arnon Avatar asked Feb 05 '23 18:02

Arnon


2 Answers

Just implement

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

If you want to customize the title you have to implement tableView:viewForFooterInSection: and return a view for example:

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
}

Side-note: Instead of calling Shared.instance.employees multiple times use a temporary variable:

let employee = Shared.instance.employees[indexPath.row]
cell.nameLabel.text = employee.name
cell.positionLabel.text = employee.position
like image 75
vadian Avatar answered Feb 13 '23 07:02

vadian


I solved the stuff doing this -> I inserted a simple label below the Prototype Cell, like this: enter image description here

Then, I just put this on viewDidLoad:

    footerLabel.text = String(Shared.instance.employees.count) + " employees"

By the way, thanks Mr vadian for your help.

like image 28
Arnon Avatar answered Feb 13 '23 06:02

Arnon