【问题标题】:how to set the selected check mark as ticked in tableview cell swift 3.0如何在tableview cell swift 3.0中设置选中的复选标记
【发布时间】:2017-12-02 16:01:56
【问题描述】:

我正在使用一个UITableView 来选择带有勾号的国家。但是当我移动到其他屏幕并且当我回来时,我的复选标记是不可见的。我选择的国家似乎很好,但是在我移动到其他屏幕后回来,选择的刻度线不存在。如何快速做到这一点。

我的代码:

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

【问题讨论】:

  • 你在哪里设置countryName
  • 它与countryName 有什么关系?您所展示的是其他一些 Instance 属性的声明。
  • 当您返回时,countryName 会保持不变!!
  • @NiravD 我已经在这里更新了我的完整代码。现在国家名称是语言名称..如果我得到解决方案,..我也可以为其他屏幕实现同样的方法

标签: ios iphone swift xcode uitableview


【解决方案1】:

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

保存已检查的多个值。

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

【讨论】:

    【解决方案2】:

    请使用以下我更正和测试的代码,它会存储上次更改的语言,即使您移动其他屏幕并返回时也会得到它

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

    查看参考图片:

    【讨论】:

    • 您可以根据自己的方便更改语言数组和注册单元格并进行测试。
    【解决方案3】:
    1. 创建另一个选定项目数组
    2. 此处 option1[indexPath.row] 将此元素与另一个数组的所有元素进行比较

    给你:-

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

    【讨论】:

    • 我已经创建了像 selectedlang = [] 这样的数组。但不知道在哪里声明..你能不能用我上面的代码来帮助我在哪里需要准确
    • 现在,当我选择任何选项表单视图时,甚至不显示勾选标记...并且也不显示所选选项
    • 我对表格视图一无所知...因为我现在没有时间从头开始学习..所以只有我发布了所以..至少我能得到答案如果我将来有任何问题,将帮助我再次解决
    • 但是这个概念还可以……但不知道如何应用我不知道如何解决……
    【解决方案4】:

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

    2) 然后与option1[indexPath.row]比较

    例子

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

    然后得到它

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

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多