【问题标题】:Save UIButton Change State in Realm Swift 3 with Notification Center使用通知中心在 Realm Swift 3 中保存 UIButton 更改状态
【发布时间】:2017-03-10 19:17:13
【问题描述】:

我有一个按钮,其发送者会观察通知并在触发后更改其标题。在触发之前,按钮标题为“A”。触发后,按钮标题为“B”。

我正在尝试将更改的状态保存在 Realm 中,以便用户可以看到按钮已更改。

发布(触发)通知发生在另一个添加 UIView 的按钮操作中。该子视图拥有发布通知:

 NotificationCenter.default.post(name: fireNotification, object: nil)

当帖子被触发时,另一个添加(观察者)通知会作用于这个事件:

// MARK: - Observe Notification

    NotificationCenter.default.addObserver(forName: fireNotification, object: nil, queue: nil) { notification in
        print("Notification Observed")

        sender.setTitle("B", for: .normal)
        sender.setTitleColor(.red, for: .normal)
        sender.isEnabled = false
    } 

这显然将按钮状态更改为 B。我如何编写并将其保存到我的领域?我试过了:

// MARK: - Observe Notification

    NotificationCenter.default.addObserver(forName: fireNotification, object: nil, queue: nil) { notification in
    print("Notification Observed")

      let realm = try! Realm()
      try! realm.write {
        sender.setTitle("B", for: .normal)
        sender.setTitleColor(.red, for: .normal)
        sender.isEnabled = false
          } 
      } 

我应该在对象参数中添加一些东西吗?

【问题讨论】:

    标签: ios notifications swift3 uibutton realm


    【解决方案1】:

    为了能够在 Realm 中保存数据,您需要创建自己的 RealmObject 子类并定义它的属性。不能保存非RealmObjects的状态。

    请查看文档以了解有关 Realm 的更多信息:https://realm.io/docs/swift/latest/

    【讨论】:

    • 嘿德米特里,你介意给我举个例子吗? Button 不是 Realm 支持的类型,因此不能用作属性。我尝试使用数据,但这也不起作用。我已经通过故事板尝试了从插座和动作到以编程方式创建按钮、打开isSelected 甚至使用UIImage(named: "abc") 的所有排列。我阅读了文档。表格视图或集合视图中的自定义按钮没有任何示例。
    • 作为记录,我也在使用领域通知(这很棒!)但无法在 IndexPath 保存所选项目的状态,因为按钮没有 IndexPath。
    猜你喜欢
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多