一般建議每詢問後讓你得到清晰的反應&不要混用主題1層的問題,但...
在Xcode故事板「屬性檢查器」,您可以更改「自動收縮」從「固定字體大小」到最小字體大小或比例。另外,將「Lines」從默認值1更改爲0.您還需要設置一些AutoLayout約束,以便將標籤固定到超級視圖或其他元素,以允許縮放。不能說更多沒有看故事板。
通過使用可選鏈來設置標籤文本,您試圖將標籤的.text
屬性設置爲可選類型String?
而不是String
。那些不相同。可選的String?
可能包含一個字符串,或者它可能爲零。 UILabel期望您使用String
實例,因此它抱怨不匹配。
一種方法是明確檢查可選值對nil
:
if currentPerson != nil {
title.text = "\(currentPerson.name) \(currentPerson.surname)"
}
else {
title.text = ""
}
斯威夫特的可選綁定類似於第一個選項,但你創建一個臨時的常數,可以參考其屬性。如果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與最小字體規模,我增加了約束,甚至底部約束。我的標籤在我的BottomNavigationBar下。我可以在我的StoryBoard上使用Playground,或者我必須每次構建? – monkeyUser