在 DidSelectRowAt 之后保存新数据

Save New Data After DidSelectRowAt

我想将新数据保存到我的 languageTitles 中,以便能够从我的 table 视图中 select 另一个单元格。现在默认值出现在我的 table 视图中,当我点击另一个单元格时,它会删除之前 selected 的单元格,但我无法 select 另一个单元格。

var languageViewModel = LanguageViewModel()
var languageTitles: [LanguageModel] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return languageCell(indexPath: indexPath)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var item = languageTitles[indexPath.row]
    let value = item.isSelected
     // Edit isSelected property and refresh table
    for index in languageTitles.indices {
        languageTitles[index].isSelected = false
        languageViewModel.setLanguageTitles(index: index)
    }
    item.isSelected = !value
    tableView.reloadData()
}

private func languageCell(indexPath: IndexPath) -> LanguageTableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: LanguageTableViewCell.identifier, for: indexPath) as! LanguageTableViewCell
    let item = languageTitles[indexPath.row]
    if item.isSelected {
        cell.setupSelected(item)
    } else {
        cell.setup(item)
    }
    return cell
}



 import Foundation
class LanguageViewModel {
    var locales: [Language] = [.tr, .eng, .az] //.ar
    var currentLanguage = UserDefaultsUtil.getDeviceLanguage()
    var languages: [LanguageModel] = []
    func getLanguageTitles() {
        languages = [
            LanguageModel(language: .tr, isSelected: currentLanguage == locales[0].code),
            LanguageModel(language: .eng, isSelected: currentLanguage == locales[1].code),
            LanguageModel(language: .az,  isSelected: currentLanguage == locales[2].code)
        ]
    }
    func setLanguageTitles(index: Int) {
        languages = [
            LanguageModel(language: .tr, isSelected: index == 0),
            LanguageModel(language: .eng, isSelected: index == 1),
            LanguageModel(language: .az,  isSelected: index == 2)
        ]
    }
}

    struct LanguageModel {
    var language: Language
    var isSelected: Bool
}

您的语言模型是结构化的,因此当您从结构数组创建新实例时,该实例不再引用数组项。

因此您需要更改数组[index] 的选定值。

item.isSelected = !value替换为

languageTitles[indexPath.row].isSelected = !value