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.
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 :
@IBDesignable
tagUIView
property with @IBInspectable
, then you will be able to change the value for this property using StoryBoardwillSet
of that property which is observer for changes before the property takes the value, or didSet
after the property received the value.prepareForInterfaceBuilder()
which is overriding from its super class kind of UIView
Simple and easy !
Your code should looks like this :
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 ;)