Ограничьте выбор в UITableView до 2

#ios #swift #xcode

Вопрос:

Как я могу ограничить выбор строки в tableview 2.

Я имею в виду, что у меня есть представление таблицы с элементами, но пользователь может выбирать неограниченное количество строк. Я хочу установить максимум 2 выбранных строки.

Я просто составил список выбранных и поместил в него элементы, и если этот список .количество >= 2, отобразите предупреждение. Но 3-я строка выбрана, даже если отображается предупреждение.

     func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        print("Tableview setup (listeSirops.count) items")
        return listeSirops.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "siropCell", for: indexPath) as? ChoisirSiropTableViewCell else {
            fatalError("Unable to dequeue tabacCell")
        }
        let tabac = listeSirops[indexPath.row]
        
        
        
        cell.labelNom.text = tabac.nom
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sirops = listeSirops[indexPath.row]
        if(listeSiropsSelected.count >= 2) {
            let alert = UIAlertController(title: "Erreur", message: "Vous ne pouvez choisir que 2 sirops.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
            }))
            self.present(alert, animated: true, completion: nil)
        } else {
            listeSiropsSelected.append(sirops.nom)
            print(listeSiropsSelected)
        }
        

        
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
        let sirops = listeSirops[indexPath.row]
        let objectToRemove = sirops.nom
        
        listeSiropsSelected.remove(object: objectToRemove)
        
        print(listeSiropsSelected)
    }

 

выбрано 3 строки, появится сообщение, но как удалить 3-ю строку ?
изображение

Ответ №1:

Реализуйте willSelectRowAt , это предотвращает выделение ячейки, если nil возвращается

 func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    return listeSiropsSelected.count < 3 ? indexPath : nil
}
 

Удалите предупреждение, оно не нужно, пользовательский опыт заключается в том, что пользователь не может выбрать более 2 ячеек.

Ответ №2:

Просто добавьте эту строку под self.present :

 tableView.deselectRow(at: indexPath, animated: true)
 

Ответ №3:

 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    //here
    if let selectedRows = tableView.indexPathsForSelectedRows, selectedRows.count > 2, let oldestIndexPath = selectedRows.first {
        tableView.deselectRow(at: oldestIndexPath, animated: true)
    }
    
    let sirops = listeSirops[indexPath.row]
    let objectToRemove = sirops.nom
    
    listeSiropsSelected.remove(object: objectToRemove)
    
    print(listeSiropsSelected)
}