我有这样一种情况,我需要根据各种条件更改文本标签,但是我不知道如何迭代在情节提要中创建的标签,而不必像下面这样将其全部写出。在下面的示例中,我首先检查数组项是否存在,如果存在,则更改标签文本和颜色。如果不存在,我想只是一个空白文本和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
}
编辑:我被要求展示故事板的结构。请看下面。这些是通过拖放一个接一个地放置在XIB文件上的标签。
这些都通过IBOutlet添加到swift文件中:
1条答案
按热度按时间6mzjoqzu1#
假设标题标签是项标签的兄弟,则可以枚举所有项标签的数组,
或者,您也可以将这四个标签作为故事板中另一个视图(可能是
UIStackView
)的子视图,这样层次结构就变成:然后,为stack视图添加一个outlet,这样就可以使用
cell.stackView.arrangedSubviews
,而不是写出itemLabels
数组。如果你想更进一步,不要使用固定数量的条目标签!而是根据
currentObjective.items
动态地将它们添加到堆栈视图中。