4

I am making a demo for learning how @IBInspectable works.

First, I made two variables in UIViewController subclass:

  @IBInspectable var intTest:Int = 10
  @IBInspectable var flag:Bool = false

So that it appears in the storyboard. After that, I change the value of those variables in the storyboard:

enter image description here

Then, I try to print those variables in "viewDidLoad()" method like this:

  override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view, typically from a nib.
       print("intTest value: \(String(describing: intTest))")
       print("flag value: \(String(describing: flag)))")
  }

The output is:

intTest value: 90

flag value: true

It works fine, except when I change the variables declaration like,

  @IBInspectable var intTest:Int? = 10
  @IBInspectable var flag:Bool? = false

After that, I changed the value same as above in the storyboard, but the values are not changed.

Output is:

intTest value: Optional(10)

flag value: Optional(false)

So my question is, why is the value not updated when i declare the variable as optional?

The another thing is, when I take the variable as a string the value is updated. Can anyone help me understand this functionality?

Jim Simson
  • 2,774
  • 3
  • 22
  • 30
vikas prajapati
  • 1,868
  • 2
  • 18
  • 26

2 Answers2

4

Set Optional value IBInspectable var

@IBInspectable var placeHolderImage:UIImage? {
     didSet {
         leftViewSetting()
     }
 }

Set default value IBInspectable var

@IBInspectable var placeHolderImage:UIImage = UIImage() {
    didSet {
        leftViewSetting()
    }
}

Using this approach and every time you change the value in Interface Builder`, your view will be updated.

@IBInspectable var cornerRadius: CGFloat {
    get {
       return layer.cornerRadius
    }
    set {
       layer.cornerRadius = newValue
    }
}
Harshal Valanda
  • 5,331
  • 26
  • 63
-1

You can declare it as an optional and it works well . Just tweak your code as below:

 @IBInspectable var intTest: Int? {
        didSet {
            self.intTestTweak = intTest
        }
  }

willSet and didSet are explained here.

Community
  • 1
  • 1
ankit
  • 3,537
  • 1
  • 16
  • 32