Search code examples
iosswiftuistoryboardibdesignableuibackgroundcolor

@IBDesignable UIView not calling init within storyboard


I have a UIView that is is @IBDesignable

@IBDesignable
class MyView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }

    private func sharedInit(){
        translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = .blue
    }

}

When I place this a UIView in the Storyboard, and assigned its class to MyView in the Identity inspector, the UIView still has a default background colour. Why is its background colour not UIColor.blue in the Storyboard? And, how can I make it like this, please?

Thanks for any help.


Solution

  • Initializer which initialize this view from storyboard will call on runtime, for updating view within storyboard in compile time you should try to include prepareForInterfaceBuilder which updates storyboard xib files in compile time.

    I suggest you to do multiple things when you are going to create @IBDesignable classes :

    1. Mark class with @IBDesignable tag
    2. Mark UIView property with @IBInspectable, then you will be able to change the value for this property using StoryBoard
    3. Set the configuration code in willSet of that property which is observer for changes before the property takes the value, or didSet after the property received the value.
    4. Do your additional setup in prepareForInterfaceBuilder() which is overriding from its super class kind of UIView

    Simple and easy !

    Your code should looks like this :

    Swift 5 :

    import UIKit
    
    @IBDesignable
    class myView: UIView {
    
      @IBInspectable var storyBoardColor : UIColor = .red {         
        willSet(myVariableNameToCatch) {
          self.backgroundColor = myVariableNameToCatch
        }
       }
    
      fileprivate func sharedInit(){
        translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = storyBoardColor
      }
    
      override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        sharedInit()
      }
    }
    

    myView had initial value of red for storyBoardColor and you can change it from storyBoard ;)

    enter image description here