[英]How do to I push another viewController to the screen without having storyboard file ? I've tried the following code but nothing happens
[英]How do I iterate through storyboard elements without having to write out everything?
我有這樣的情況,我需要根據各種條件更改文本 label,但我不知道如何遍歷在 Storyboard 中創建的標簽,而不必像下面這樣全部寫出來。 在下面的示例中,我首先檢查數組項是否存在,如果存在,則更改 label 文本和顏色。 如果沒有,我只想要空白文本和 UIColor 黑色的默認設置。 標簽被添加到 XIB 單元格中。
if let item1 = currentObjective.items[safe: 0] {
cell.item1Label.text = item1.title
cell.item1Label?.textColor = returnColor(item: item1)
} else {
cell.item1Label.text = ""
cell.item1Label?.textColor = UIColor.black
}
if let item2 = currentObjective.items[safe: 1] {
cell.item2Label.text = item2.title
cell.item2Label?.textColor = returnColor(item: item2)
} else {
cell.item2Label.text = ""
cell.item2Label?.textColor = UIColor.black
}
if let item3 = currentObjective.items[safe: 2] {
cell.item3Label.text = item3.title
cell.item3Label?.textColor = returnColor(item: item3)
} else {
cell.item3Label.text = ""
cell.item3Label?.textColor = UIColor.black
}
編輯:我被要求展示 storyboard 的結構。請看下面。 這些是通過拖放逐一放置在 XIB 文件上的標簽。
假設title label是item labels的兄弟,你可以枚舉所有item labels的數組,
let itemLabels = [
cell.item1Label!,
cell.item2Label!,
cell.item3Label!,
cell.item4Label!,
]
for (i, label) in itemLabels.enumerated() {
if let item = currentObjective.items[safe: i] {
label.text = item.title
label.textColor = returnColor(item: item)
} else {
label.text = ""
label.textColor = UIColor.black
}
}
或者,您也可以將這四個標簽作為另一個視圖(可能是UIStackView
)的子視圖放在 storyboard 中,這樣層次結構就變成了:
ObjectiveCell
UIStackView
item1Label
item2Label
item3Label
item4Label
titleLabel
然后,為堆棧視圖添加一個出口。 這樣,您可以使用cell.stackView.arrangedSubviews
,而不是寫出itemLabels
數組。
如果您想 go 更進一步,請不要使用固定數量的項目標簽,而是基於currentObjective.items
將它們動態添加到堆棧視圖中。
// remove all the existing items first (I'm guessing you're doing this in cellForRowAt or something like that)
cell.stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
for item in currentObjective.items {
let label = UILabel()
label.text = item.title
label.textColor = returnColor(item: item)
cell.stackView.addArrangedSubview(label)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.