【问题标题】:How to save the state of the checkbox to core data in Swift?如何将复选框的状态保存到 Swift 中的核心数据?
【发布时间】:2017-06-22 12:25:45
【问题描述】:

**我的英语不好。请原谅我笨拙的英语。

我正在使用复选框处理待办事项列表项目。我找不到将复选框状态保存到核心数据的方法

这是我现在使用的代码的一部分。 Tasks 是实体(类定义),它具有 isMarked 作为布尔属性。 (为了简单起见,我删减了很多,所以如果你发现代码中有什么奇怪的地方,请写评论)

import UIKit
import CoreData

var toDolist: [Tasks] = []

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(toDoTable)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBOutlet weak var toDoTable: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return toDolist.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
        cell.box.setImage(#imageLiteral(resourceName: "uncheckedbox"), for: .normal)

        let task = toDolist[indexPath.row]

        return cell
    }

    func getData(){
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do{
            toDolist = try context.fetch(Tasks.fetchRequest())
        }catch{
            print("fetching failed")
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        getData()
        toDoTable.reloadData()
    }

}


class CustomTableViewCell: UITableViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    @IBOutlet weak var box: CheckBox!
    @IBOutlet weak var taskLbl: UILabel!
}

class CheckBox{
    var isChecked: Bool = false{
        didSet{
            if isChecked == true{
                self.setImage(#imageLiteral(resourceName: "checkedbox"), for: .normal)
            }else{
                self.setImage(#imageLiteral(resourceName: "uncheckedbox"), for: .normal)
            }
        }
    }

    override func awakeFromNib(){
        self.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)
        self.isChecked = false
    }

    func buttonClicked(_ sender: UIButton){
        if sender == self{
            if isChecked == true{
                isChecked = false
            }else{
                isChecked = true
            }
        }
    }
}

如何通过添加一些代码来解决这个问题?还是我必须更改上面的所有代码?

【问题讨论】:

  • 您必须(通过引用)将数据模型(Task 实例)连接到按钮的状态和操作。最方便的方法是将cellForRow 中的Task 实例传递给自定义表格视图单元格。由于引用语义,任何更改都将持续存在,您只需要保存托管对象上下文。实际上继承 UIButton 是多余的。
  • @vadian 我删除了 'UIButton' 子类,但是如何将 'cellForRow' 中的 'Tasks' 实例(您的意思是 'cellForRowAt' ?)传递给自定义 tableview 单元格?你的意思是我必须选择手动/无而不是类定义?对不起,我只是编程和英语的初学者......
  • • 在单元格中添加属性var task : Tasks! 并在cellForRowAt 中添加一行cell.task = task。现在您将数据源项移交给了单元格。 • 将didSet 观察者添加到task 以将isChecked 设置为当前值。 • 在单元格中添加IBAction 以接收触摸并在Interface Builder 中连接。 • 在操作切换isChecked 中,更新task 中的图像和属性。 • 保存上下文。
  • "在单元格中添加一个'IBAction'"是指在函数'cellForRowAt'中添加它?我做不到,我尝试在 func cellForRowAt 中添加目标框,但我也无法使其正常工作。或者我应该在单元格上添加一个新的透明操作按钮吗?对于这些连续的基本问题,我们深表歉意。
  • 不,在单元格中表示在CustomTableViewCell类中(按钮所属的地方)。

标签: swift xcode core-data checkbox


【解决方案1】:

简单的解决方案:

  • 删除UIButton 的子类并将按钮的类恢复为UIButton。
  • 在 Interface Builder 中,将图像 checkedbox 和 uncheckedbox 分配给状态 selected 和 default 的按钮。图像会根据按钮的isSelected 属性自动显示。这完全避免了更新代码中的图像。

  • CustomTableViewCell 类获得属性task 和IBAction,该IBAction 必须连接到按钮的Touch Up Inside。 task的属性isSelected必须改成NSManagedObject的属性名

    class CustomTableViewCell: UITableViewCell {
    
        @IBOutlet weak var box: UIButton!
        @IBOutlet weak var taskLbl: UILabel!
    
        var task : Tasks! {
            didSet {
                box.isSelected = task.isSelected
                taskLbl.text = // update the label
            }
        }
    
        @IBAction func buttonClicked(_ sender: UIButton)
        {
            let selected = !sender.isSelected
            sender.isSelected = selected
            task.isSelected = selected
            // save the context if needed
        }
    
    }
    
  • 在cellForRowAt 中添加行来分配task

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
        let task = toDolist[indexPath.row]
        cell.task = task
        return cell
    }
    

【讨论】:

  • 实际上实体Tasks 具有isMarked 作为其属性,但除此之外,它工作得很好!非常感谢。(对不起,我不能投票,因为我似乎缺乏足够的声誉或类似的东西......)
猜你喜欢
  • 2016-08-19
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
  • 1970-01-01
相关资源
最近更新 更多