0

I want to make an @IBInspectable for UIView that makes UIView as a circle:

@IBInspectable var circleBorder: Bool {
    set {
       layer.cornerRadius = layer.frame.size.width / 2
    }
    get {
        return layer.cornerRadius > 0 ? true : false
    }
}

The problem is that my @IBInspectable is called before constraints modifies its value and a wrong cornerRadius is being set. Is it possible to get the layer size after constraints here?

Roo
  • 613
  • 1
  • 7
  • 24

1 Answers1

1

I don't think there is, but there's a better way - expose cornerRadius.

This way the developer can do things in their own sequence. Exposing things in a Bool means that in IB a developer needs to (1) create the view, (2) add the constraints, (3) update the frames, and then (4) set the Bool. (Also, in Xcode 8, I'm guessing if you change the device in IB - even after getting the sequence correct - things may not properly update.

Unless you have a specific reason - which I can't come up with - to make this a Bool, this is not only harmless, it is more customizable.

The code:

@IBInspectable public var cornerRadius:CGFloat {
    get {
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
}
  • Yes, I've been using this. But I faced the problem that if UIView size is dynamic and the constraints changes it the cornerRadius must change too. – Roo May 05 '17 at 12:02
  • I see what you are saying. You may not be able to accomplish what you want 100%. :-( In my eyes, this gets down to IB being a *design-time* tool and "a perfect circle" (`frame.size.width/2`) being a *runtime* calculation. I had the same kind of thing happen - I wanted to move a set of controls from the bottom to the right, depending on the orientation. IB couldn't handle it, because iPads have the same size class no matter the orientation. I ended up ditching IB entirely, as it's easily done in code! –  May 05 '17 at 12:16