0

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.

 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:

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

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.

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.

4

2 回答 2

1

您不需要将参数传递给 didSet 。状态本身已经是 didSet 中的新参数,因此您可以使用此更改 didSet 代码块;

didSet {

        print("PRINT didSet \(state)")

            switch state {
            case .unlock:
            self.backgroundColor = green   
            }
            self.setNeedsDisplay()     
    }
于 2017-06-29T12:42:14.147 回答
0
class DeviceView: UIView {
    var state:State?  {
        didSet(newValue) {
        print("PRINT didSet \(newValue)")
            switch newValue {
            case .unlock:
            self.backgroundColor = green   
            }
        self.setNeedsDisplay()     
}   

像这样试试。

于 2017-06-29T12:33:00.783 回答