xcode 如何迭代故事板元素而不必写出所有内容?

2ul0zpep  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(96)

我有这样一种情况,我需要根据各种条件更改文本标签,但是我不知道如何迭代在情节提要中创建的标签,而不必像下面这样将其全部写出。在下面的示例中,我首先检查数组项是否存在,如果存在,则更改标签文本和颜色。如果不存在,我想只是一个空白文本和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文件中:

6mzjoqzu

6mzjoqzu1#

假设标题标签是项标签的兄弟,则可以枚举所有项标签的数组,

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)的子视图,这样层次结构就变成:

ObjectiveCell
    UIStackView
        item1Label
        item2Label
        item3Label
        item4Label
    titleLabel

然后,为stack视图添加一个outlet,这样就可以使用cell.stackView.arrangedSubviews,而不是写出itemLabels数组。
如果你想更进一步,不要使用固定数量的条目标签!而是根据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)
}

相关问题