How to make not all cells in a tableView editable?

Asked

Viewed 28 times

0

I have a tableView where the user can delete the cells he selects. In my case the first cell of the tableView cannot be deleted by the user. How do I make only the first cell of the tableView not editable?

class ViewController: UIViewController {
    @IBOutlet var tableView: UITableView!
    var users = ["Todos", "User1", "User2", "User3", "User5"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = user.name

        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            self.users.remove(at: indexPath.row)
        }
    }
}

1 answer

1


I searched the tableView delegate and found the tableView(_:editingStyleForRowAt:) function implemented this way:

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    // Todos os indíces da tableView serão editáveis para exclusão menos o primeiro (índex == 0)
    if indexPath.row != 0 {
        return .delete
    }
    return .none
}

It broke the branch and was working fine. Until digging through the Stack I found this solution infinitely more attractive:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath != 0
}

It turns out that using this tableView(_:canEditRowAt:) function, in addition to code reduction, does not make the non-enterable cells go a little to the right:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.