Ios UILabel自动调整Swift的大小
我正在学习Swift,但我有两个“愚蠢”的问题 首先,我想自动调整UILabel的大小 第二,我有另一个UIlabel,我想把名字和姓氏放在它的字段中 我试过了Ios UILabel自动调整Swift的大小,ios,swift,Ios,Swift,我正在学习Swift,但我有两个“愚蠢”的问题 首先,我想自动调整UILabel的大小 第二,我有另一个UIlabel,我想把名字和姓氏放在它的字段中 我试过了 @IBOutlet weak var title: UILabel! title.text = currentPerson?.name+""+currentPerson?.surname 但我有这个错误 可选类型“字符串”的值未展开;你是想用 “!”还是“?” 一般建议每个帖子问一个问题,这样你就能得到清晰的回答&不要混淆主题,但是
@IBOutlet weak var title: UILabel!
title.text = currentPerson?.name+""+currentPerson?.surname
但我有这个错误
可选类型“字符串”的值未展开;你是想用
“!”还是“?”
一般建议每个帖子问一个问题,这样你就能得到清晰的回答&不要混淆主题,但是
.text
属性设置为可选类型字符串?
,而不是字符串。这些并不等同。String?
类型的可选项可能包含字符串,也可能是nil。UILabel希望您使用字符串
实例,因此它抱怨不匹配
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 = ""
}
或者,如错误消息所示,您可以强制展开可选值以访问名称属性:
title.text = currentPerson!.name + " " + currentPerson!.surname
这假设currentPerson
从不为零。如果为零,您的应用程序将在此崩溃
另外请注意,您可以使用
+
和“
或字符串插值进行连接。感谢您的回复,字符串是concat。关于我的第一个问题。我用最小字体比例修改了Autoshrink,添加了约束,甚至是底部约束。我的标签在底部导航栏下。我可以用我的故事板使用游乐场,还是每次我都要构建?