Home > Enterprise >  Best place to make a UIView subclass round
Best place to make a UIView subclass round

Time:11-02

I have a UIView subclass that needs to be round. The issue I am having is that this view is instantiated with frame .zero (and eventually resized) which produces a cornerRadius of 0 when calling makeRound in the initializer.

Which UIView lifecycle method should I call makeRound and assume layer.bounds has adopted its final value (which is non-zero)?

fileprivate extension UIView {
    func makeRound() {
        layer.cornerRadius = layer.bounds.width*0.5
        clipsToBounds = true
    }
}

The only UIView subclass initializer I can use is

    public init() {
        super.init(frame: .zero)
        // init routines
    }

CodePudding user response:

I would either override the bounds property or override the layoutSubviews method.

class SomeView: UIView {
    // Either do this:
    override var bounds: CGRect {
        didSet {
            layer.cornerRadius = bounds.size.height / 2.0
            // or call makeRound()
        }
    }

    // Or do this:
    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = bounds.size.height / 2.0
        // or call makeRound()
    }
}

Don't do both. Pick the one of the two.

  • Related