Background Color Not Rendering In Storyboard When Using IBDesignable

Hi,


In the following code, the button's background color is not rendering in storyboard however it does appear in the simulator. The border properties render in storyboard it's just the background color which is not working.



import UIKit

let colorSunset = #colorLiteral(red: 0.9693382382, green: 0.5568749309, blue: 0, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        buttonA()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        buttonA()
    }
    
    
    func buttonA() {
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 5
        self.layer.backgroundColor = colorSunset.cgColor
    }
    
}


Thanks

Accepted Reply

Here is something that works :


@IBDesignable class PrimaryButtonA: UIButton {
    
     override init(frame: CGRect) {
          super.init(frame: frame)
          buttonA()
     }
     required init?(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
          buttonA()
     }
    
     override func prepareForInterfaceBuilder() {
          super.prepareForInterfaceBuilder()
          backgroundColor = colorSunset
         
     }

     func buttonA() {
          self.layer.cornerRadius = 10
          self.layer.borderWidth = 5
//          self.layer.backgroundColor = colorSunset.cgColor
     }
    
}


And the indepth explanation was found here (brilliant):

h ttps://stackoverflow.com/questions/39347255/ibdesignable-view-doesnt-draw-background-color-inside-interface-builder


While rendering in Interface builder(IB), the properties which are set in IB of custom UI element are loaded after the call to

init
.

Replies

Here is something that works :


@IBDesignable class PrimaryButtonA: UIButton {
    
     override init(frame: CGRect) {
          super.init(frame: frame)
          buttonA()
     }
     required init?(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
          buttonA()
     }
    
     override func prepareForInterfaceBuilder() {
          super.prepareForInterfaceBuilder()
          backgroundColor = colorSunset
         
     }

     func buttonA() {
          self.layer.cornerRadius = 10
          self.layer.borderWidth = 5
//          self.layer.backgroundColor = colorSunset.cgColor
     }
    
}


And the indepth explanation was found here (brilliant):

h ttps://stackoverflow.com/questions/39347255/ibdesignable-view-doesnt-draw-background-color-inside-interface-builder


While rendering in Interface builder(IB), the properties which are set in IB of custom UI element are loaded after the call to

init
.

Thanks Claude, your solution worked perfectly.