可变UILabel名称

问题描述 投票:0回答:2

是否可以将标签设为变量?我有多个标签:

@IBOutlet weak var FL1at0: UIButton!
@IBOutlet weak var FL1at3: UIButton!
@IBOutlet weak var FL1at6: UIButton!
@IBOutlet weak var FL1at9: UIButton!
@IBOutlet weak var FL1at12: UIButton!
@IBOutlet weak var FL1at15: UIButton!
@IBOutlet weak var FL1at18: UIButton!
@IBOutlet weak var FL1at21: UIButton!

示例功能:

       else
       {
           UserDefaults.standard.set(true, forKey: "RedFl1")
           self.FL1at0.setTitleColor(UIColor.red, for: .normal); self.ProgressUpdate()
       }

有没有一种方法可以像这样设置表格:

self.FL1at"\(TimeStamp)".setTitleColor(UIColor.red, for: .normal)//TimeStamp comes from function
swift variables uibutton uilabel
2个回答
1
投票

尝试一下:

let dict: Dictionary<String, UIButton> = ["FL1at0": FL1at0, "FL1at3": FL1at3, ...]
let x = "FL1at\(TimeStamp)"
if let y = dict[x] as? UIButton {
    y.setTitleColor(UIColor.red, for: .normal)
}

1
投票

你不能。但是您可以将按钮保存在字典中:

var dic: [String: UIButton] = ["FL1at0": FL1at0]

然后您可以使用名称来访问它,例如:

dic["FL1at\(TimeStamp)"]?.setTitleColorxxxx..
© www.soinside.com 2019 - 2024. All rights reserved.