我在学斯威夫特,但我有两个“愚蠢”的问题。
第一,我想自动调整我的UILabel的大小,第二,我有另一个UIlabel,我想在它的字段中加上名字和姓氏
我试过
@IBOutlet weak var title: UILabel!
title.text = currentPerson?.name+""+currentPerson?.surname但我有个错误
值的可选类型‘字符串?’不是拆开的,你是故意用"!“或者"?“?
发布于 2014-12-31 00:15:10
一般建议每个帖子问一个问题,这样你就能得到清晰的回答&不要混淆话题,但是.
.text属性设置为可选类型String?,而不是String。那可不是等价物。String?类型的可选项可能包含字符串,也可能为零。UILabel希望您使用一个String实例,因此它在抱怨不匹配。一种方法是显式地根据nil检查可选值。
if currentPerson != nil {
title.text = "\(currentPerson.name) \(currentPerson.surname)"
}
else {
title.text = ""
}Swift的可选绑定类似于第一个选项,但您可以创建一个临时常量,并可以引用其属性。如果currentPerson不是nil,则执行if块。
// current convention would be to use "currentPerson" on both sides, which can be confusing. The left side is a temporary constant & the right side is the optional property you've declared somewhere above
if let aPerson = currentPerson {
title.text = "\(aPerson.name) \(aPerson.surname)"
}
else {
title.text = ""
}或者,正如错误消息所示,您可以强制打开可选值以访问name属性:
title.text = currentPerson!.name + " " + currentPerson!.surname这假设currentPerson永远不会为零。如果是零,你的应用程序就会在这里崩溃。
还请注意,您可以使用+和" "或字符串内插连接。
https://stackoverflow.com/questions/27713348
复制相似问题