swiftuiimageviewinitializationoverridingsubclass

How to initialize an empty object of a custom UIImageView subclass


I'm having a custom UIImageView subclass which runs some basic code like creating a shadow etc. When I don't override any init everything works fine. I can create an empty CustomImageView() the same way I would create am empty UIImageView() . The moment I'm adding all the required overrides I cannot create an empty object anymore.

The error I am getting is:

Cannot invoke initializer for type 'ProfilePictureImageView' with no arguments

with the suggestion:

  1. Overloads for 'ProfilePictureImageView' exist with these partially matching parameter lists: (coder: NSCoder), (frame: CGRect), (image: UIImage?)

I create the empty object in my view controller like this:

var customImageView = CustomImageView()

And my custom UIImageView subclass looks like this:

class CustomImageView: UIImageView {
    
    override init(image: UIImage?) {
        super.init(image: image)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }


// Followed by my custom variables and methods.

}

I've tried to add the following, assuming I'm missing an empty init of some sort. But this didn't work either.

override init() {
    super.init()
}

Solution

  • You've to make a convenience init method.

    class CustomImageView: UIImageView {
        //...
        convenience init() {
            self.init(frame: .zero) // or self.init(image: nil)
        }
    }