Скольжение по табличному виду отменяет выбор всех выбранных строк. TrailingSwipeActionsConfigurationForRowAt - PullRequest
3 голосов
/ 18 марта 2019

Недавно реализовано trailingSwipeActionsConfigurationForRowAt, где после пролистывания справа налево показаны две опции и все работает нормально.Но проблема в том, что, когда я выбираю несколько строк или одну строку, после прокрутки строки / строк они отменяются.Есть ли способ сохранить выделение даже после считывания?

Ниже мой код

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) ->  UISwipeActionsConfiguration?  {

    let renameAction  = contextualToggleRenameAction(forRowAtIndexPath: indexPath)
    let lastResAction = contextualToggleLastResponseAction(forRowAtIndexPath: indexPath)

    let swipeConfig = UISwipeActionsConfiguration(actions: [renameAction, lastResAction])
    swipeConfig.performsFirstActionWithFullSwipe = false
    return swipeConfig
}

func contextualToggleLastResponseAction(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
    let sensorData = sensorsList?[indexPath.row]
    var lastResponse = ""
    if sensorData != nil{
        if let lstRes = sensorData!["last_response"] as? String{
            lastResponse = lstRes
        }
    }
    let action = UIContextualAction(style: .normal, title: lastResponse) { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in
        print("Last Response Action")
    }
    action.backgroundColor = UIColor(red: 61/255, green: 108/255, blue: 169/255, alpha: 1.0)
    return action
}

Ответы [ 3 ]

1 голос
/ 25 марта 2019

В зависимости от indexPathsForSelectedRows не всегда дает ожидаемый результат.

Вместо этого вы должны поддерживать и массив selectedIndexPaths.

Вот фрагмент кода для демонстрации:

var selectedIndexPaths = [IndexPath]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedIndexPaths.contains(indexPath) {
       selectedIndexPaths.removeAll { (ip) -> Bool in
        return ip == indexPath
    }else{
       selectedIndexPaths.append(indexPath)
    }
}
1 голос
/ 25 марта 2019

Вы можете просто сделать это:

  1. Создать массив в вашем контроллере для выбранного индекса

    var arrSelectedIndex : [Int] = []
    
  2. В didSelect,

    if arrSelectedIndex.contains(indexPath.row) { // Check index is selected or not
        // If index selected, remove index from array
        let aIndex = arrSelectedIndex.firstIndex(of: indexPath.row)
        arrSelectedIndex.remove(at: aIndex!)
    }
    else {
        // If index not selected, add index to array
        arrSelectedIndex.append(indexPath.row)
    }
    // reload selected row, or reloadData()
    self.tblView.reloadRows([indexPath.row], with: .automatic)
    

Редактировать

  1. В trailingSwipeActionsConfigurationForRowAt,

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
    {
    
        if self.arrSelectedIndex.contains(indexPath.row) {
    
            let action = UIContextualAction(style: .normal, title: "") { (action, view, handler) in
    
            }
            action.backgroundColor = .green
            let configuration = UISwipeActionsConfiguration(actions: [])
            configuration.performsFirstActionWithFullSwipe = false
            return configuration
        }
        let action = UIContextualAction(style: .normal, title: "Selected") { (action, view, handler) in
    
        }
        action.backgroundColor = .green
        let configuration = UISwipeActionsConfiguration(actions: [action])
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }
    

выход

enter image description here

1 голос
/ 22 марта 2019

Проведение считается редактированием, поэтому вы можете включить allowsSelectionDuringEditing, если хотите сохранить выбранное состояние:

tableView.allowsSelectionDuringEditing = true
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...