如何在tableview单元格swift 3.0中设置选中的复选标记

时间:2017-06-29 05:19:48

标签: ios iphone swift xcode uitableview

我使用一个UITableView来选择带刻度标记的国家/地区。但当我移动到其他屏幕时,当我回来时,我的复选标记是不可见的。看起来像我选择的国家是好的,但在我移动到其他屏幕后回来,选择的刻度标记不存在。如何在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 个答案:

答案 0 :(得分:2)

1)创建另一个选定项目数组并保存它有很多选项,例如。 UserDefaults.standard

2)然后与option1[indexPath.row]

进行比较

例如

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

然后通过

获取
UserDefaults.standard.value(forKey: "selectedLanguageArray")

答案 1 :(得分:0)

  1. 创建另一个选定项目数组
  2. 此处option1 [indexPath.row]将此元素与另一个数组的所有元素进行比较
  3. 在这里: -

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

答案 2 :(得分:0)

以下是我用来保存新闻类别选择的类似代码,可以帮助您解决问题。

保存多个已检查的值。

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

答案 3 :(得分:0)

请使用我更正并测试的以下代码,它会存储最后更改的语言,即使您移动其他屏幕也会获得

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

参见参考图像:

enter image description here