Home > database >  Why does calling init() calls init(frame: CGRect)?
Why does calling init() calls init(frame: CGRect)?

Time:02-17

When I have a custom UIView with overridden init like this:

class ContainerView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setup() {
    }
}

Why am I able to initialize the view with a simple init like this and the setup() method is called?

let view = CustomView()

I would expect it to NOT be called when I'm calling the simple NSObject init() and not the init(frame: CGRect)?

How is the frame parameter passed then?

CodePudding user response:

Calling CustomView() is using an inherited initializer for NSObject. This implicitly calls UIView's designated initializer, init(frame:) with .zero. Since you've overriden that initializer, your override is called and thus the setup() method is called too.

You can see this by printing out the frame parameter in your initializer; you will get a .zero rect.

  • Related