简体   繁体   English

如何在TableView Cell Swift 3.0中将选中的选中标记设置为勾选

[英]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. 我正在使用一个UITableView选择带有刻度的国家。 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 : 我的代码:

    @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()
        }
    }

1) create another array of selected items and save it there are so many options eg. 1)创建另一个数组的选定项目,并保存它有这么多的选择,例如。 UserDefaults.standard

2) then compare with option1[indexPath.row] 2)然后与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 在这里,option1 [indexPath.row]将此元素与另一个数组的所有元素进行比较

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()
        }
    }
}

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"]
}

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 // 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: 请参阅参考图片:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM