how to set the selected check mark as ticked in tableview cell swift 3.0

I am using one UITableView to select the country with tick mark. But when I move to other screen and when I come back my check mark is invisible. It seems like the country what I am selecting is fine, But after I move to other screen an come back, The selected tick mark is not there. How to do that in swift.

my code :

  • UICollectionView Horizontal Paging not centered
  • Apple id account belonging to two teams getting “Your account already has a valid iOS Distribution certificate”
  • How to create an NSDictionary with multiple keys?
  • How to crop the image using UIBezierPath?
  • Getting “A valid signing identity matching this profile could not be found in your keychain” warning
  • How to fetch email id from JSON file in firebase using swift
  •     @IBOutlet weak var tableView: UITableView!
        @IBOutlet weak var saveBtn: UIButton!
        var languageName : String = String()
    
        var option : [String] = ["English","हिंदी"]
        var option1 : [String] = []
        let availableLanguages = Localize.availableLanguages()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.tableFooterView = UIView()
            for language in availableLanguages {
                option1.append(language)
                let displayName = Localize.displayNameForLanguage(language)
    
            }
    
        }
    
    
    
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
        }
    
    
    
        //MARK: - TableView
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return option1.count
        }
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 60
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
            cell.textLabel?.text = option[indexPath.row]
    
            if option1[indexPath.row] == languageName{
                cell.accessoryType = UITableViewCellAccessoryType.checkmark
            }else{
                cell.accessoryType = UITableViewCellAccessoryType.none
            }
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            languageName = option1[indexPath.row]
            self.tableView.reloadData()
        }
    
    
        @IBAction func saveButtonPressed(_ sender: Any) {
            Localize.setCurrentLanguage(languageName)
            if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
                appdelegate.showHomeLandingScreen()
            }
        }
    

    4 Solutions Collect From Internet About “how to set the selected check mark as ticked in tableview cell swift 3.0”

    1) create another array of selected items and save it there are so many options eg. UserDefaults.standard

    2) then compare with option1[indexPath.row]

    example

    UserDefaults.standard.set(selectedLanguageArray, forKey: "selectedLanguageArray")
    UserDefaults.standard.synchronize()
    

    Then get it by

    UserDefaults.standard.value(forKey: "selectedLanguageArray")
    
    1. create another array of selected items
    2. here option1[indexPath.row] compare this element with all element of another array

    Here you go:-

     @IBOutlet weak var tableView: UITableView!
        @IBOutlet weak var saveBtn: UIButton!
        var languageName : String = String()
    
        var option : [String] = ["English","हिंदी"]
        var selectedlang: [String] = []
    
        let availableLanguages = Localize.availableLanguages()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.tableFooterView = UIView()
            for language in availableLanguages {
                option1.append(language)
                let displayName = Localize.displayNameForLanguage(language)
    
            }
    
        }
    
    
    
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
        }
    
    
    
        //MARK: - TableView
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return option1.count
        }
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 60
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
            cell.textLabel?.text = option[indexPath.row]
    
    
            for (index,element) in selectedlang.enumerated(){
    
                if element == option[indexPath.row]{
    
                    cell.accessoryType = UITableViewCellAccessoryType.checkmark
    
    
                }else{
    
                    cell.accessoryType = UITableViewCellAccessoryType.none
    
    
    
                }
    
    
            }
             return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            languageName = option1[indexPath.row]
    
    
    
            for (index,element) in newArr.enumerated(){
    
                if element == languageName{
    
                    selectedlang.remove(at: index)
    
                }else{
    
                    selectedlang.append(languageName)
    
    
                }
    
    
            }
    
    
    
            self.tableView.reloadData()
        }
    
    
        @IBAction func saveButtonPressed(_ sender: Any) {
            Localize.setCurrentLanguage(languageName)
            if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
                appdelegate.showHomeLandingScreen()
            }
        }
    }
    

    Please use below code which i corrected and tested, It stores last changed language and will get it even when you move other screen an come back

    // ViewController.swift

    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        @IBOutlet weak var tableView: UITableView!
        @IBOutlet weak var saveBtn: UIButton!
        var languageName : String?
    
        var option : [String] = ["English","हिंदी","French","Dutch"] //Your languages displays in table view
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    
            languageName = UserDefaults.standard.value(forKey: "MyselectedLanguage") as? String //Your last selected language fetch
            self.tableView.reloadData()
        }
    
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
        }
    
        //MARK: - TableView
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return option.count
        }
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 60
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    
            cell.textLabel?.text = option[indexPath.row]
    
            if option[indexPath.row] == languageName{
                cell.accessoryType = UITableViewCellAccessoryType.checkmark
            }else{
                cell.accessoryType = UITableViewCellAccessoryType.none
            }
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            languageName = option[indexPath.row]
            self.tableView.reloadData()
        }
    
    
        @IBAction func saveButtonPressed(_ sender: Any) {
    
            UserDefaults.standard.set(languageName, forKey: "MyselectedLanguage")
            UserDefaults.standard.synchronize()
    
            if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
                appdelegate.showHomeLandingScreen()
            }
        }
    }
    

    See the reference Image:

    enter image description here

    Here is a similar code that I use to save News category selections, should help you with your problem.

    Saves multiple values that are checked.

    class ViewController {
        var selectedCategoriesArray = [Any]()
    
        private var appSettings: UserDefaults?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            appSettings = UserDefaults.standard
            loadNewsSelectedCategories()
        }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellNewsCategory", for: indexPath)
        // Configure the cell...
        cell?.textLabel?.text = "\(newsCategoriesArray[indexPath.row])"
        let cellText: String? = cell?.textLabel?.text
        for lbl: String in selectedNewsCategories {
            if (cellText == lbl) {
                cell?.accessoryType = .checkmark
                break
            }
            else {
                cell?.accessoryType = []
            }
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let selectedCell: UITableViewCell? = tableView.cellForRow(at: indexPath)
        let selectedCategory: String? = selectedCell?.textLabel?.text
        if tableView.cellForRow(at: indexPath)?.accessoryType == [] {
            tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
            print("\(selectedCategory)")
            selectedCategoriesArray += selectedNewsCategories
            selectedCategoriesArray.append(selectedCategory)
            let categories: [Any] = NSOrderedSet(selectedCategoriesArray).array()
            print("+categories:\n \(categories)")
            appSettings["selectedNewsCategories"] = categories
        }
    else if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        tableView.cellForRow(at: indexPath)?.accessoryType = []
        print("\(selectedCategory)")
        loadNewsSelectedCategories()
        selectedCategoriesArray += selectedNewsCategories
    selectedCategoriesArray.remove(at: selectedCategoriesArray.index(of: selectedCategory)!)
    
        var categories: [Any] = NSOrderedSet(selectedCategoriesArray).array()
        print("-categories:\n \(categories)")
        appSettings["selectedNewsCategories"] = categories
    }
    else {
        tableView.cellForRow(at: indexPath)?.accessoryType = []
    }
    appSettings.synchronize()
    }
    func loadNewsSelectedCategories() {
        selectedNewsCategories = [Any]()
        selectedNewsCategories = appSettings["selectedNewsCategories"]
    }