Search code examples
swiftuikit

Best place to make a UIView subclass round


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
    }

Solution

  • 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.