Search code examples
iosswiftuiviewcalayer

Change CALayer color in sync with UIView tintColor when a UIViewController presents a popover


In iOS, when a UIViewController presents a popover, its view's tintColor will change to a b/w color (that way, buttons look non-clickable while the popover is visible). When the popover is dismissed, the color will change back.

There is a subclass of a UIView that hold badge count. This views layer's color is supposed to have the same color as the view's tintColor.

How to synchronize the tintColor for the sublayer within its superview?

// draw orange background layer with border  
override func draw(_ rect: CGRect) {
    layer.cornerRadius = rect.height / 2
    layer.borderColor = UIColor.orange.cgColor
    layer.borderWidth = 2
    layer.backgroundColor = UIColor.white.cgColor
    layer.masksToBounds = true
}

Default:

enter image description here

Presented:

enter image description here


Solution

  • Override tintColorDidChange in custom UIView and set tintColor to layer's backgroundColor in it.

    override func tintColorDidChange() {
        layer.backgroundColor = tintColor.cgColor
    }
    

    enter image description here