user8969667
user8969667

Reputation:

When I scroll down in my TableView, the cell data changes - Swift 4

When I scroll down in my Table View, the cell data that has disappeared then changes. How can I solve this?

class TableViewController: UITableViewController {

    var number = 1
    let finishNumber = 10

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return finishNumber
    }

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

        cell.textLabel?.text = "\(number)"

        number = number + 1

        return cell
    }
}

Upvotes: 0

Views: 1510

Answers (2)

Supanat Techasothon
Supanat Techasothon

Reputation: 415

Unclear question but I think you want to scroll to bottom when tableview reload right ?

extension UITableView {
    func scrollToBottom(animated: Bool = false) {
        let section = self.numberOfSections
        if (section > 0) {
            let row = self.numberOfRows(inSection: section - 1)
            if (row > 0) {
                 self.scrollToRow(at: IndexPath(row: row - 1, section: section - 1), at: .bottom, animated: animated)
            }
        }
    }
}

When calling, you need to use "async"

DispatchQueue.main.async(execute: {
    yourTableView.reloadData()
    yourTableView.scrollToBottom()
}

Good luck.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

You update number every time the table view asks for a cell. That has no direct relation to the row being displayed.

It's unclear why you even have the number property.

If you just want to show the corresponding row number in each cell, get rid of the number property and update:

cell.textLabel?.text = "\(number)"

with:

cell.textLabel?.text = "\(indexPath.row)"

Upvotes: 1

Related Questions