@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

enter image description here

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 enter image description here

When I set clearColor

to the background of my views, the result is: enter image description here

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.

+3


source to share


2 answers


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:

enter image description here

Look for an elegant solution - the method that does it for me.

0


source


Try this: The frame of the subView must be equal to the bounds of the placeHolder. iee



subView.frame = placeholder.bounds;

      

-1


source







All Articles