在 Watchkit 中基于分页的界面共享数据

Share data in paged based interface in Watchkit

我需要从第一页开始与所有页面共享一个字符串。 我试图用 didDeactive() 来做到这一点,但它不起作用。 甚至可以这样做吗?

很难说出您真正想做什么,所以我要进行一些推断。我 "think" 您正在尝试从第一页设置一些共享值并能够在其他页面中使用该值。如果是这种情况,那么您可以执行以下操作:

class SharedData {
    var value1 = "some initial value"
    var value2 = "some other initial value"

    class var sharedInstance: SharedData {
        struct Singleton { static let instance = SharedData() }
        return Singleton.instance
    }

    private init() {
        // No-op
    }
}

class Page1InterfaceController: WKInterfaceController {
    func buttonTapped() {
        SharedData.sharedInstance.value1 = "Something new that the others care about"
    }
}

class Page2InterfaceController: WKInterfaceController {
    @IBOutlet var label: WKInterfaceLabel!

    override func willActivate() {
        super.willActivate()

        self.label.setText(SharedData.sharedInstance.value1)
    }
}

SharedData 对象是一个单例 class,它是一个全局对象。任何人都可以从任何地方访问它。在我提供的小示例中,Page1InterfaceController 正在处理 buttonTapped 事件并将 SharedData 实例的 value 属性 更改为新值。然后,当滑动到 Page2InterfaceController 时,新值显示在 label.

这是一个对象间共享数据的超级简单示例。希望这能帮助您朝着正确的方向前进。