2016-03-21 28 views
-1

我現在從一個WKInterfaceController一個字符串值傳遞到另一個使用contextForSegueWithIdentifier像這樣:Watchkit - 如何傳遞多個值與contextForSegueWithIdentifier

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

回答

1

Swift有三種收集類型:Array,DictionarySet

傳遞上下文作爲一個字符串數組:

... 
    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"]) 
    } 
} 

個人而言,我更喜歡使用的字典,作爲該陣列的方法如果調用者改變了順序或者字符串的數量,它會更加脆弱。

無論哪種方式,添加必要的檢查,使您的代碼健壯。