我正在学习 Swift,但我有两个“愚蠢”的问题。
首先,我想自动调整我的 UILabel 第二,我有另一个 UIlabel,我想在它的字段中输入名字和姓氏
我试过
@IBOutlet weak var title: UILabel!
title.text = currentPerson?.name+""+currentPerson?.surname
但是我有这个错误
Value of optional type 'String?' not unwrapped; did you mean to use "!" or "?" ?
最佳答案
通常建议每个帖子问 1 个问题,这样您就可以得到明确的答复并且不要混淆主题,但是...
在 XCode Storyboard“Attributes Inspector”中,您可以将“Autoshrink”从“Fixed Font Size”更改为最小字体大小或比例。还将“Lines”从默认值 1 更改为 0。您还需要设置一些 AutoLayout 约束以将标签固定到 superview 或其他元素,使其能够缩放。没有看到 Storyboard就不能说更多。
通过使用可选链接设置标签文本,您尝试将标签的
.text
属性设置为可选类型String?
而不是字符串
。那些不等同。String?
类型的可选类型 可能 包含一个字符串,或者它可能为 nil。 UILabel 希望您使用String
实例,因此它会提示不匹配。
一种方法是根据 nil
显式检查可选值:
if currentPerson != nil {
title.text = "\(currentPerson.name) \(currentPerson.surname)"
}
else {
title.text = ""
}
Swift 的可选绑定(bind)类似于第一个选项,但是你创建了一个临时常量并可以引用它的属性。如果 currentPerson
不是 nil
,则执行 if
block 。
// 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
永远不会为 nil。如果它是 nil,您的应用程序将在这里崩溃。
另请注意,您可以使用 +
和 ""
或字符串插值来连接。
关于ios - UILabel 自动调整大小 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713348/