I have a UIView with different states defined with an enum. When I change the state, I would like to update its backgroundColor propertys. It doesn't work.
我有一个用枚举定义的不同状态的UIView。当我改变状态时,我想更新它的backgroundColor属性。它不起作用。
enum State {
case lock
case unlock
case done
}
@IBDesignable
class DeviceView: UIView {
var state:State = .lock {
didSet(newValue) {
print("PRINT didSet \(newValue)")
switch newValue {
case .unlock:
self.backgroundColor = green
}
self.setNeedsDisplay()
}
}
func initDevice(type:Type) {
self.state = state
}
In my view controller in viewDidLoad:
在viewDidLoad中的视图控制器中:
override func viewDidLoad() {
device1View.initDevice(state: .lock)
print("PRINT 1 \(device1View.state)")
}
Later in another place, I need to change the state of my DeviceView
稍后在另一个地方,我需要更改我的DeviceView的状态
print("PRINT 2 \(device1View.state)")
device1View.state = .unlock
print("PRINT new 3 \(device1View.state)")
The result:
结果:
PRINT didSet lock
PRINT 1 lock
PRINT 2 lock
PRINT didSet lock <--- ???
PRINT new 3 done
...and so on my backgroundColor is never updated.
...等我的backgroundColor永远不会更新。
I don't understand why the last didSet is "lock". It should be "unlock" no ? I think it's the reason why my background color isn't updated.
我不明白为什么最后的didSet是“锁定”。应该“解锁”不?我认为这就是为什么我的背景颜色没有更新的原因。
2 个解决方案
#1
1
You don't need to pass parameter to didSet . The state itself is already the new parameter in the didSet so you may change didSet code block with this;
您不需要将参数传递给didSet。状态本身已经是didSet中的新参数,因此您可以使用此更改didSet代码块;
didSet {
print("PRINT didSet \(state)")
switch state {
case .unlock:
self.backgroundColor = green
}
self.setNeedsDisplay()
}
#2
0
class DeviceView: UIView {
var state:State? {
didSet(newValue) {
print("PRINT didSet \(newValue)")
switch newValue {
case .unlock:
self.backgroundColor = green
}
self.setNeedsDisplay()
}
Try like this.
试试这样吧。
#1
1
You don't need to pass parameter to didSet . The state itself is already the new parameter in the didSet so you may change didSet code block with this;
您不需要将参数传递给didSet。状态本身已经是didSet中的新参数,因此您可以使用此更改didSet代码块;
didSet {
print("PRINT didSet \(state)")
switch state {
case .unlock:
self.backgroundColor = green
}
self.setNeedsDisplay()
}
#2
0
class DeviceView: UIView {
var state:State? {
didSet(newValue) {
print("PRINT didSet \(newValue)")
switch newValue {
case .unlock:
self.backgroundColor = green
}
self.setNeedsDisplay()
}
Try like this.
试试这样吧。