[英]iOS/Swift 4: change color from a programmatically created label
我根據數組的數量創建了幾個標簽。 而且效果很好。 但是在發生一些用戶交互之后,我想更改標簽顏色。
這是我的代碼:
-數組看起來像這樣:
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屏幕上看到的標簽。
可能的解決方案之一 。
在類的某個地方創建您在第一個循環中創建的UILabel的存儲。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.