【问题标题】:Watchkit - How pass multiple values with contextForSegueWithIdentifierWatchkit - 如何使用 contextForSegueWithIdentifier 传递多个值
【发布时间】:2016-03-21 00:34:51
【问题描述】:

我目前使用contextForSegueWithIdentifier 将字符串值从一个WKInterfaceController 传递到另一个,如下所示:

override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {

    if segueIdentifier == "segueDetails" {
        return self.string1
    }

    // Return data to be accessed in ResultsController
    return nil
}

然后在目的地WKInterfaceController 我执行以下操作:

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    if let val: String = context as? String {
        self.label.setText(val)
    } else {
        self.label.setText("")
    }
    // Configure interface objects here.
}

但是,我想传递多个值,使用两个附加的字符串值属性,称为string2string3

如何将其他字符串值传递给WKInterfaceController

【问题讨论】:

    标签: swift segue watchkit watchos-2


    【解决方案1】:

    Swift 具有三种集合类型:ArrayDictionarySet

    将上下文作为字符串数组传递:

        ...
        if segueIdentifier == "segueDetails" {
            return [string1, string2, string3]
        }
    
    func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
    
        // Configure interface objects here.
        if let strings = context as? [String] {
            foo.setText(strings[0])
            bar.setText(strings[1])
            baz.setText(strings[2])
        }
    }
    

    将上下文作为字典传递:

        ...
        if segueIdentifier == "segueDetails" {
            return ["foo" : string1, "bar" : string2, "baz" : string3]
        }
    
    func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
    
        // Configure interface objects here.
        if let strings = context as? [String: String] {
            foo.setText(strings["foo"])
            bar.setText(strings["bar"])
            baz.setText(strings["baz"])
        }
    }
    

    就我个人而言,我更喜欢使用字典,因为如果调用者更改了顺序或字符串的数量,数组方法会更加脆弱。

    无论哪种方式,添加必要的检查以使您的代码健壮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多