Search code examples
swiftinterface-builderxibnibuibackgroundcolor

How to setup UIView in a nib/xib to get background colour different in runtime but not interface builder


I'm building reusable views in xib/nib files and I have some view that need to render .clear during runtime but... My superviews that will be presenting these nibs are dark and therefore when I design these nibs they have a white background and its hard to see my text and other controls on these views.

In other, is it possible to have a background colour black for example in the interface builder and at runtime they are clear?


Solution

  • You can add a User defined Runtime attribute from the inspector on your view controller in storyboard to adjust your background color on runtime.

    User Defined Runtime Attributes screenshot

    Note: The key path is backgroundColor

    Or just set the backgroundColor in awakeFromNib(). This function get's called once the nib has been loaded.

    override func awakeFromNib() {
        super.awakeFromNib()
    
        backgroundColor = .blue
    }