保存&使用Swift中的NSUserDefaults检索TableViewCell复选标记

时间:2016-09-03 12:58:26

标签: swift

我正在尝试使用NSUserDefaults.My部分代码保存和检索tableViewCell复选标记,如下所示。从代码中,我可以使用UITableViewCellAccessoryType选择或取消选择单元格。我不熟悉在Swift中使用NSUserDefaults。请某人指点我方向......

    override func viewDidLoad() {
    super.viewDidLoad()
    self.myTableView.allowsMultipleSelection = true
    let userDefaults = NSUserDefaults.standardUserDefaults()
    }

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
    }

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) 
    cell.textLabel!.text = myItems[indexPath.row] as? String
    cell.selectionStyle = .None
    cell.tintColor = UIColor.greenColor()

    return cell
}

先谢谢。

2 个答案:

答案 0 :(得分:1)

  • 首先创建一个类Item作为具有nameselected属性的数据源。

    class Item {
      let name : String
      var selected = false
    
      init(name: String) {
        self.name = name
      }
    }
    
  • 声明数据源数组

    var myItems = [Item]()
    
  • 以这种方式创建项目

    let item = Item(name:"Foo") // your former string value, `selected` is false by default.
    myItems.append(item)
    
  • applicationDidFinishLaunching中注册一个空字符串数组作为键selectedCells的默认值

    let defaults = NSUserDefaults.standardUserDefaults()
    let defaultValues = ["selectedCells" : [String]()]
    defaults.registerDefaults(defaultValues)
    
  • 要从用户默认值中读取所有选定的单元格,请获取字符串数组,并将所有相应项目的属性selected设置为true。然后重新加载表视图。强制解包是安全的,因为键/值是预先注册的并且始终是非可选的。 重要提示:确保在注册默认值后始终将readDefaults()称为

    func readDefaults()
    {
      let defaults = NSUserDefaults.standardUserDefaults()
      let selectedItems = defaults.stringArrayForKey("selectedCells")!
      for item in myItems {
        item.selected = selectedItems.contains(item.name)
      }
      tableView.reloadData()
    }
    
  • cellForRowAtIndexPath中相应地设置两个属性

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
      let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath)
      let item = myItems[indexPath.row]
      cell.textLabel!.text = item.name
      cell.accessoryType = item.selected ? .Checkmark : .None
      cell.selectionStyle = .None
      cell.tintColor = UIColor.greenColor()
    
      return cell
    }
    
  • 要保存数据过滤所有selected属性为true的项目,请将其映射到名称并保存数组。

    func saveDefaults() {
      let selectedCells = myItems.filter { $0.selected }.map { $0.name }
      let defaults = NSUserDefaults.standardUserDefaults()
      defaults.setObject(selectedCells, forKey:"selectedCells")
    }
    
  • 现在您应该更改didSelectRowAtIndexPath中的模型并重新加载该行。这比操纵单元格更有效(和推荐)

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      let item = myItems[indexPath.row]
      item.selected = true
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
    }
    

答案 1 :(得分:0)

我的示例,我在DetailController中设置的tableView中加载

模型----

struct TheoryData {

    var id: String
    var theoryText: String
    var theoryModes: String
    var theoryImage: String
    var like: Bool
}

读取值

   var theoryData = [TheoryData]()

private func readDefaults() {
    let defaults = UserDefaults.standard
    let selectedItems = defaults.stringArray(forKey: "selectedCells") ?? []
    
    (0..<theoryData.count).forEach { i in
        theoryData[i].like = selectedItems.contains(theoryData[i].id)
    }
    menuTableView.reloadData()
}

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    readDefaults()
}

在单元格中

let theory = theoryData[indexPath.row]
cell.likeImage.image = theory.like ? #imageLiteral(resourceName: "heart-icon") : #imageLiteral(resourceName: "heart-empty-icon")

在UserDefault中保存状态

    @IBAction func likeButtonTapped(_ sender: UIButton) {
        theoryData.like.toggle()
        let likeIcon = theoryData.like ? #imageLiteral(resourceName: "heart-icon") : #imageLiteral(resourceName: "heart-empty-icon")
        likeButton.setImage(likeIcon, for: .normal)
        saveSelection()
    }
    
    private func saveSelection() {
        let defaults = UserDefaults.standard
        var selectedItems = defaults.stringArray(forKey: "selectedCell") ?? []
        
        if theoryData.like {
            selectedItems.append(theoryData.id)
        } else {
            selectedItems = selectedItems.filter{ $0 != theoryData.id }
        }
        print(selectedItems)
        defaults.setValue(selectedItems, forKey: "selectedCell")
    }
 }