IBDesignable加载xib时未设置view.frame

时间:2017-07-29 20:34:09

标签: swift uiview interface-builder ibdesignable

我有一个简单的UIView子类,我已经@IBDesignable。 我重载了init frameinit coder。我的代码从.xib文件加载视图描述。 加载.xib文件后,我尝试设置:

view.clipsToBounds = true
view.layer.cornerRadius = frame.size.height / 2

获得“带圆形边的矩形”。

问题是当时frame.size.height = 0(加载.xib后我的自定义视图首次由Interface Builder绘制)。

有解决方法吗?

这是我的代码:

@IBDesignable
class CustomUIVIew: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

    private var view: UIView!
    private let nibName = "CustomUIView"

    private func xibSetup() {

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(view)
        setupView()
    }

    private func loadViewFromNib() -> UIView {

        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        return view
    }

    private func setupView() {

        view.clipsToBounds = true
        view.layer.cornerRadius = frame.size.height / 2
    }
}

谢谢你,卢卡 -

2 个答案:

答案 0 :(得分:2)

您应该将任何与尺码相关的调整移至layoutSubviews。这样,不仅可以在IB中正确呈现,还可以在设备上呈现,如果窗口大小发生变化,cornerRadius将相应调整。

答案 1 :(得分:1)

prepareForInterfaceBuilder完成了这项工作

override func prepareForInterfaceBuilder() {
    view.clipsToBounds = true
    view.layer.cornerRadius = bounds.height / 2
}