xcode 我应该如何在 Swift 的标签中获取变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24186962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I get variable in label in Swift?
提问by AMHD
I'm new to Swift, so I made a new iOS project. I have declared a variable and placed a content into it. Also I have created IBOutlet
for label and I tried to get a variable in my label. Swift compiler said: 'UInt32' is not convertible to 'String'
.
我是 Swift 的新手,所以我做了一个新的 iOS 项目。我已经声明了一个变量并将内容放入其中。我也IBOutlet
为标签创建了,我试图在我的标签中获取一个变量。Swift 编译器说:'UInt32' is not convertible to 'String'
.
What's wrong with my code?
我的代码有什么问题?
class ViewController: UIViewController {
@IBOutlet var Mark : UILabel
@IBAction func Rate(sender : UIButton) {
var chibotar = arc4random_uniform(6)
Mark.text = chibotar // error on this line
}
回答by Jean-Philippe Pellet
You need to convert it to a String. You have several ways to do it in this case:
您需要将其转换为字符串。在这种情况下,您有几种方法可以做到:
let chibotar = arc4random_uniform(6) // let instead of var for constants
Mark.text = String(chibotar)
Mark.text = chibotar.description
Mark.text = "\(chibotar)"
回答by PREMKUMAR
Just change the following line
只需更改以下行
Label will display String Values so convert to Sting using following Line.
Label 将显示字符串值,因此使用以下行转换为 Sting。
var chibotar = arc4random_uniform(6)
Mark.text = "\(chibota)"
//(or)
Mark.text = String(chibotar)
It will work
它会工作