Проблема удаления одной строки из таблицы с несколькими разделами (Swift 4) - PullRequest
0 голосов
/ 14 сентября 2018

Я пытаюсь удалить строку из раздела в моей таблице с несколькими разделами, используя commit editStyle. Тем не менее, он удаляет правильный indexPath.row из раздела выше.

Как мне заставить его удалить из соответствующего раздела?

Я следовал нескольким примерам о том, как разделить отдельный массив и проиндексировать его для tableView. Я не могу правильно удалить из исходного массива объектов пользовательских классов. Я также не могу найти способ передать раздел и строку IndexPath во второй контроллер представления для отображения выбранного кода. Он просто передает indexPath.row, но я не могу заставить его отправить весь indexPath, включая раздел.

   func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if tableView == firstTableView {
        if editingStyle == .delete { 
            if inSearchMode == false {
                codeArray.remove(at: [indexPath.section][indexPath.row])
                userDefaults.setValue(NSKeyedArchiver.archivedData(withRootObject: codeArray), forKey: "codeArrayKey")
                userDefaults.synchronize()
                tableView.reloadData()
            }
        }
    }
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let subArrayArray = codeArray.compactMap { $0.subArray as? String }
    var dic = [String:[Code]]()
    subArrayArray.forEach {
        let subArrayKey = $0
        let filterArray = codeArray.filter { $0.subArray as? String == subArrayKey }
        dic[$0] = filterArray
    }

    let sectionTitle = sectionTitles[section]
    let sectionCodes:[Code] = dic[sectionTitle]!

    if tableView == firstTableView {
        if inSearchMode == true {
            return filteredCodeArray.count
        } else {
            return sectionCodes.count
        }
    } else if tableView == autoTableview {
        return locationFilteredCodeArray.count
    } else {
        return 1
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    if tableView == firstTableView {
        if inSearchMode == false {
            indexCodes(enterArray: codeArray)
            return sectionTitles.count
        } else if inSearchMode == true {
            return 1
        }
    }
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == firstTableView {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "newCodesProtoCell") as? NewCodesViewCell {
            let code: Code!

            if inSearchMode == true {
                code = filteredCodeArray[indexPath.row]
                cell.configureCell(code: code)
            } else {

                let subArrayArray = codeArray.compactMap { $0.subArray }
                var dic = [String:[Code]]()
                subArrayArray.forEach {
                    let subArrayKey = $0
                    let filterArray = codeArray.filter { $0.subArray == subArrayKey }
                    dic[$0] = filterArray
                }

                let sectionTitle = sectionTitles[indexPath.section]
                let sectionCodes:[Code] = dic[sectionTitle]!
                code = sectionCodes[indexPath.row]
                cell.configureCell(code: code)
            }
            return cell
        }
    }
    if let cell = tableView.dequeueReusableCell(withIdentifier: "secondNewCodesProtoCell") as? SecondNewCodesProtoCell {
        let code: Code!
        if locationFilteredCodeArray.count != 0 {
            locationAuthStatus()
            code = locationFilteredCodeArray[indexPath.row]
            cell.configureSecondCell(code: code)
        }
        return cell
    }

    return UITableViewCell()
}

Вот так я получаю массив имен индексов (заголовков), поскольку это может вызывать некоторые проблемы. Это написано для индексации [Код] по второй букве в .location.

func indexCodes(enterArray: [Code]) {
    var codeValues = [String]()
    for code in enterArray {
        var initCodeKey = String(code.location.prefix(2))
        initCodeKey.remove(at: initCodeKey.startIndex)
        let codeKey = initCodeKey.capitalized
        codeValues.append(codeKey)
    }

    var encountered = Set<String>()
    var result: [String] = []
    for value in codeValues {
        if encountered.contains(value) {
        } else {
            encountered.insert(value)
            result.append(value)
        }
    }
    sectionTitles = result.sorted(by: <)
}

1 Ответ

0 голосов
/ 14 сентября 2018

Вам нужно сделать 2 шага.1. Из вашего codeArray получите словарь из indexPath.section, а затем ваш объект Code из [Code], сохраненный в этом словаре.Удалите код в indexPath.row, а затем зарезервируйте его в словарь и замените объект словаря в CodeArray 2. self.tableView.reloadRows (at: [IndexPath (row: 0, section: 0)], с: .fade)

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if tableView == firstTableView {
        if editingStyle == .delete { 
            if inSearchMode == false {
                codeArray.remove(at: [indexPath.section][indexPath.row])
var dict = codeArray[indexPath.section]
let key = dict.allKeys.first
var codes = dict[key]

//remove code from [Code]
codes.remove(at: indexPath.row)
dict[key] = codes
codeArray[indexPath.section] = dict
                userDefaults.setValue(NSKeyedArchiver.archivedData(withRootObject: codeArray), forKey: "codeArrayKey")
                userDefaults.synchronize()
                self.tableView.reloadRows(at: [IndexPath(row: indexPath.row,       section: indexPath.section)], with: .fade)
            }
        }
    }

сообщите мне, если вы обнаружите какие-либо проблемы с его реализацией.

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