Home > Enterprise >  Save New Data After DidSelectRowAt
Save New Data After DidSelectRowAt

Time:03-30

I want to save new data to my languageTitles to be able to select another cell from my table view. Right now default value is coming on my table view and when I tap on another cell it deletes the previously selected cell but I can not select another when tapped.

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
}

CodePudding user response:

Your language model is struct so when you create new instance from struct array, this instance not referencing array item anymore.

Therefore you need to change array[index] selected value.

replace item.isSelected = !value to

languageTitles[indexPath.row].isSelected = !value
  • Related