1

Trying to show the button background color in the storyboard, the following code renders the border width and radius correctly but background doesn't show. In the simulator, the button's background color is rendered correctly.

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
    }


}

Code Screenshot

Storyboard Screenshot

Simulator Screenshot

Xcode doesn't show any errors but there is a warning which is unrelated and is about the button's fixed width and height and the text will be clipped.

Thanks in advance for the help.

Raj
  • 35
  • 9
  • 1
    Possible duplicate of [@IBDesignable view doesn't draw background color inside Interface Builder](https://stackoverflow.com/questions/39347255/ibdesignable-view-doesnt-draw-background-color-inside-interface-builder) – Kazi Abdullah Al Mamun Aug 27 '18 at 05:06
  • @Kazi, I did come upon that article before I posted the question but that solution didn't work for me or I probably implemented it wrong. Also the question was posted in 2016 and I was hoping there is a better solution for this in 2018. – Raj Aug 27 '18 at 06:15
  • @Raj please read answer carefully of that duplicate question, you will understand why background color is not changing in storyboard. I believe that answer is also applicable for 2018. please let us know if you find better solution. Thank you. – Kazi Abdullah Al Mamun Aug 27 '18 at 07:44
  • @KaziAbdullahAlMamun Yes, I implemented the override func too but same issue, doesn't render the background color in storyboard but does render in simulator. – Raj Aug 28 '18 at 01:09
  • @Raj but overriding method is working for me. – Kazi Abdullah Al Mamun Aug 28 '18 at 03:30

2 Answers2

2

This is the solution that worked for me.

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()
}

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    backgroundColor = colorSunset
}


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

}
Raj
  • 35
  • 9
-1

There is no solution to this. This problem occurs because some times storyboard does not recognize IBDesignables. When you restart your XCode sometimes it gets recognized and sometimes it doesn't.