【问题标题】:How to save checkmark in Swift?如何在 Swift 中保存复选标记?
【发布时间】:2019-03-02 13:03:05
【问题描述】:

我正在为自己制作一个待办事项应用程序,并且我想制作一个功能来将待办事项标记为已完成。它添加了一个复选标记,字体应该变成灰色,但我是编码新手,所以我真的不知道如何将字体颜色和复选标记保存到内存中。我不知道我是否应该将它保存到 userdefaults 或核心数据,最重要的是如何保存它。非常感谢任何帮助。

代码如下: 我想保存 textColor 和 accesoryType

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let done = UIContextualAction(style: .normal, title: "Done") { (action, view, nil) in
        print("Done")
        tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.lightGray
       tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    done.backgroundColor = .blue
    let config = UISwipeActionsConfiguration(actions: [done])
    config.performsFirstActionWithFullSwipe = false
    return config           
}

【问题讨论】:

    标签: swift xcode uitableview core-data nsuserdefaults


    【解决方案1】:

    在你的数据模型中添加一个属性

    var isDone : Bool = false
    

    cellForRow中根据该属性设置UI(假设datasourceArray是数据源数组)

    let item = datasourceArray[indexPath.row]
    cell.textColor = item.isDone ? .lightGray : .blue
    cell.accessoryType = item.isDone ? .checkmark : .none
    

    在操作中将isDone 属性设置为true 并重新加载行。

    let done = UIContextualAction(style: .normal, title: "Done") { (action, view, nil) in
        print("Done")
        self.datasourceArray[indexPath.row].isDone = true
        self.tableView.reloadRows(at: [indexPath], with: .none)
    }
    

    并删除

    done.backgroundColor = .blue
    

    【讨论】:

    • 非常感谢您的回答,但我没有迈出第一步。我了解其余部分,但是如何将 var isDone : Bool = false 添加到数据模型中?
    • 数据模型是数据源数组中的类型,最好是struct或者class。
    • 好的,我这样做了,但现在显示错误。 “'NSManagedObject' 类型的值在 cell.textColor = item.isDone 中没有成员 'isDone'”。
    • 您必须在 Core Data 实体中添加 isDone 作为 Bool 属性。
    • 根据实体代码创建设置,您可以在NSManagedObject 子类中手动添加@NSManaged 属性,
    【解决方案2】:

    您可以使用 var status: Bool 来添加待办事项?将其存储在数据库中。 您可以通过 setup(status) 设置带有状态的复选标记 希望能帮到你!

    【讨论】:

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