Swift:将变量插入标签?

时间:2016-04-08 20:54:44

标签: swift variables label

我想在UIViewController标签中插入一个变量字符:

e.g。 “Currency = $”当$是变量且可能 $,£,€取决于。

你是如何用这个来编程的?

4 个答案:

答案 0 :(得分:2)

你会这样做:

var letter = "$"
// You create a new uilabel named label
label.text = "Currency = " + letter

你想根据你的条件改变你的字母var。

以下是一个例子:

// var currency is a string used to
// read a paragraph 
 If(currency == "dollar") 
      letter = "$"
 Else if (currency == "British pound")
      letter = "£"
 Else if (currency == "yen")
      letter = "¥"
 ...

 label.text = "Currency = " + letter

以下是参考:strings and characters: Apple

希望这有帮助!

答案 1 :(得分:2)

我认为最好的方法是为每个货币字符创建单独的变量,然后将它们附加到字符串中。然后,您可以将该标签的文本设置为该字符串。

let currencyCharacter:String = "$"
let viewControllerLabelText:String = "Currency = " + currencyCharacter
myViewControllerLabel.text = viewControllerLabelText

答案 2 :(得分:1)

您可以通过将变量包装在\()中来使用字符串插值,如下所示:

let currency = "$"
currencyLabel.text = "Currency = \(currency)"

这会将该变量的值插入到周围的字符串中。 在此处查看有关此主题的更多信息:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

答案 3 :(得分:1)

这是一个干净的方法:

func currencySymbol(currency: String) -> String {
    switch currency {
        case "dollar": return "$"
        case "British pound": return "£"
        case "yen": return "¥"
        ///add others as needed
        default: return currency
    }
}

let string =  "Currency = \(currencySymbol("dollar"))"    //"Currency = $"