简体   繁体   中英

Why doesn't setting backgroundColor have a visible effect on my custom UIView?

When I set the backgroundColor property of my Xib-instantiated subclass of UIView , the view's background color doesn't change but rather stays the color set in the Xib.

Reproducing the issue

I have created a subclass of UIView , let's call it MyView , along with a Xib from which I instantiate it. Using Interface Builder, I have set the background color of the view in the Xib to blue.

I have added an instance of MyView as a subview of my app's main view. It appears blue, as expected.

I then added an outlet, myView , referencing that instance of MyView , and a button whose action attempts to change the view's background color like so:

@IBOutlet weak var debugView: MyView!

@IBAction func debug(_ sender: Any) {
    myView.backgroundColor = UIColor.green
}

I expected the background color of myView to change to green; instead, it stays blue like before.

Observations

Strangely, if I check the background color of the view in the debugger, it seems that the property has been set to green, as expected, even though the change isn't visible:

(lldb) p debugView.backgroundColor == UIColor.blue
(Bool) $R1 = false
(lldb) p debugView.backgroundColor == UIColor.green
(Bool) $R2 = true

I have also tried forcing the view to redraw using setNeedsDisplay() , to no effect.

Why doesn't my custom view's appearance reflect its backgroundColor property?

You probably added a view from nib as subview to your customview in the swift file that is the reason on changing the backgroundcolor you would not see the changes. you need to change the background color of the subview of your debugview to see the color change. For example:-

self.debugView.subviews.first?.backgroundColor = 
    self.debugView.subviews.first?.backgroundColor == UIColor.blue
        ? UIColor.black : UIColor.blue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM