I'm a getting stuck with initializing subclass of UIView

Viewed 64

I want to create a UIView by code and I need to know 4 variables to draw this UIView. But I can't initialize this subclass.

Here is my code:

class CardView: UIView, UIGestureRecognizerDelegate{
    private(set) var character: Int
    private(set) var numberOfCharacters: Int
    private(set) var shading: Int
    private(set) var color: Int
    private(set) var identifier: Int

    init(frame: CGRect, card: Card) {
        self.character = card.character
        self.numberOfCharacters = card.numberOfCharacters
        self.color = card.color
        self.shading = card.shading
        self.identifier = card.identifier

        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder) //Error: Property 'self.character' not initialized at super.init call
    }
}

Did I miss anything?

2 Answers

The error appears because you are required to give every non-initialised property a value in every designated initialiser, before you call super.init You haven't given a value to all your properties in the init(coder:) initialiser, hence the error.

You can just call fatalError in the initialiser:

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Calling fatalError here is acceptable because you are only creating your UIView by code, so the above initialiser will not be called. It will be called when you load your view from an XIB or storyboard, in which case you have to decode the values from the NSCoder and assign the properties.

I think problem is with the variables, those are not initialized so only you may get the errors. So, please set some value to the variables are declare them like below:

private(set) var character: Int!
Related