@IBInspectable: wrong borders and frames at runtime when i add subviews
This is my code @IBInspectable:
:
@IBDesignable
class PBOView: UIView {
@IBInspectable var borderRightColor: UIColor? {
didSet {
let borderRightView = UIView(frame: CGRectMake(frame.size.width - 10, 0, 10, frame.size.height))
borderRightView.backgroundColor = borderRightColor
addSubview(borderRightView)
}
}
}
This is the result of the storyboard:
the width of the UIView is 150
and in the iPhone Simulator: the width of the UIView 150
, but it should be 80
since it's iPhone. This is why rectangles are not visible inside my custom views
When I set clearColor
to the background of my views, the result is:
Why is there a wrong border and border width in this UIViews? This is actually the width from the storyboard, not the real width at runtime.
source to share
I've dug some, but I haven't found an elegant property or method to solve this problem. So far the only way is:
@IBDesignable
class PBOView: UIView {
var borderRightView: UIView?
@IBInspectable var borderRightColor: UIColor? {
didSet {
addBorderRightView()
}
}
func addBorderRightView() {
borderRightView = UIView(frame: CGRectMake(frame.size.width - 10, 0, 10, frame.size.height))
borderRightView!.backgroundColor = borderRightColor
addSubview(borderRightView!)
}
override func layoutSubviews() {
super.layoutSubviews()
if let borderRightView = borderRightView {
borderRightView.removeFromSuperview()
}
if let borderRightColor = borderRightColor {
addBorderRightView()
}
}
}
Just override the method layoutSubviews()
with your own content. Since it layoutSubviews()
is called almost everywhere, it works as it should.
Result:
Look for an elegant solution - the method that does it for me.
source to share