Store selected cell in TableView

0

Solution to this question

https://stackoverflow.com/questions/51911991/how-can-i-save-checked-rows-of-tableview-in-userdefault/51923705?noredirect=1#comment98520742_51923705

import Foundation
import UIKit

class LocalisatorVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var tableViewLanguages: UITableView!
    @IBOutlet weak var continueBtn: UIButton!
    
    var arrayLanguages:[String] = Localisator.sharedInstance.getArrayAvailableLanguages()
    
    var selectedRow: String {
        return UserDefaults.standard.value(forKey: "CurrentLanguageKey") as? String ?? ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    
    // MARK: - UITableViewDataSource protocol conformance
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayLanguages.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellLocalisator") as? LocalisatorCell
        
        let language = arrayLanguages[indexPath.row]
        cell!.lblLanguage?.text = Localization(language)
        
        if selectedRow == language {
            cell?.imageSelected.image = UIImage(named: "checkBlueCircle.png")
        }else {
            cell?.imageSelected.image = UIImage(named: "nil")
        }
        
        return cell!
    }
    
    // MARK: - UITableViewDelegateprotocol conformance
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let language = arrayLanguages[indexPath.row]
        UserDefaults.standard.set(language, forKey: "CurrentLanguageKey")
        
        if SetLanguage(arrayLanguages[indexPath.row]) {
            let alert = UIAlertView(title: nil, message: Localization("languageChangedWarningMessage"), delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }
        
        tableViewLanguages.reloadData()
    }
}

class LocalisatorCell: UITableViewCell {
    
    @IBOutlet weak var imageSelected: UIImageView!
    @IBOutlet weak var lblLanguage: UILabel!
}
0

Leave a Reply

santoshm