使用以编程方式创建的标签中的变量显示文本

时间:2019-06-21 19:24:59

标签: swift xcode uilabel

我试图将随机数存储在变量numberSelected中并显示在label created programmatically上。我有以下代码

 var numberSelected = String()
 let numbers = ["One", "Two", "Three", "Four"]
 numberSelected = numbers.randomElement()!

let label = UILabel()
// Here text is being displayed
label.text = numbers.randomElement()

//Here text is not being displayed
label.text = numberSelected

print(label.text!)

如何使用numberSelected变量显示标签?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试以下简单修改:

 let numbers = ["One", "Two", "Three", "Four"]
 let numberSelected = numbers.randomElement()!

let label = UILabel()
// This works
label.text = numbers.randomElement()

//This won't work
label.text = numberSelected

print(label.text!)