我正在根据数组的计数创建多个标签。这很好用。但是在发生一些用户交互之后,我想更改标签颜色。
这是我的代码:
- 数组看起来像这样:
var vids = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]
for label in vids[x][1] {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.gray
label.text = vids[index[j] as! Int]![2]
let z = CGFloat(j)
self.view.addSubview(label)
let horConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 0.3+z, constant: 0.0)
let verConstraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.75, constant: 0.0)
view.addConstraints([horConstraint, verConstraint])
}
- 用户与应用程序交互后,我尝试这样做:
for label in vids[x][1] {
let label = UILabel()
label.backgroundColor = UIColor.green
}
……但什么也没发生。
如果你这样做:
for label in vids[x][1] {
let label = UILabel()
label.backgroundColor = UIColor.green
}
您的标签不会更改。问题在于,let label = UILabel()
您只需在线创建一个新的UILabel
. 这个标签不是你在 iPhone 屏幕上看到的标签。
可能的解决方案之一。
在您的班级中的某个地方创建您在第一个循环中创建的 UILabels 存储。
var vids = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]
var labels: [String: UILabel] = [:]
for labelString in vids[x][1] {
let label = UILabel()
labels[labelString] = label
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.gray
label.text = vids[index[j] as! Int]![2]
let z = CGFloat(j)
self.view.addSubview(label)
let horConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 0.3+z, constant: 0.0)
let verConstraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.75, constant: 0.0)
view.addConstraints([horConstraint, verConstraint])
}
并在以后使用它:
for labelString in vids[x][1] {
let label = labels[labelString] // < Here you retrieves a saved label
label.backgroundColor = UIColor.green
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句