按名称引用多个标签

referencing multiple labels by name

我有一个标签插座,例如

infoLabel.text = "\(windowText)"

我知道我可以通过更改“”中的文本以及变量中的值来更新标签 windowText

但我有多个标签,例如

text1 = "this is text 1"
text2 = "this is text 2"
text3 = "this is text 3"

我希望能够更新 infoLabel 以根据按 UI 按钮增加的计数器来引用 text1、text2、text3 之一,但我似乎无法让它工作。

所以如果 generalCounter = 3

如何让我的标签引用名为 text(counterGeneral) 的字符串 如果再次按下并且 generalCounter 现在为 4,则标签现在需要引用 text(4).

您可以创建 array of strings:

let texts : [String] = [/* Your strings... */]

然后在您的 Interface Builder 操作中相应地更新您的标签

// The function with is called when a press of your UIButton occur
@IBAction updateLabel(_ sender: UIButton) {

    // Verify there are a next string 
    if generalCounter + 1 < texts.count {

        generalCounter += 1
        infoLabel.text = texts[generalCounter]
    }
}

您可以使用一个 Outlet 集合,一个 UILabel 数组来简单地遍历每个 同时为

保留多少更改文本的计数器