achntrl
achntrl

Reputation: 23

I don't know to initialize my variable in the required init?(coder) method of my UIView subclass

I want to initialize the presenter attribute of my UIView subclass, I do it in my init method but I have the error "Property 'self.presenter' not initialized at super.init call" in the required init?(coder) method.

I don't know how to initialize it since I can't add arguments to the required init?(coder) method.

class HorizontalBarChart: UIView {
    private var presenter: HorizontalBarChartPresenter

    init(barHeight: CGFloat, spaceBetweenBars: CGFloat) {
        self.presenter = HorizontalBarChartPresenter(barHeight: barHeight, spaceBetweenBars: spaceBetweenBars)
        super.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Upvotes: 1

Views: 220

Answers (1)

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9925

If your UI is defined in a Storyboard or Nib files then defining a convinience intitializers or overriding exisitng ones is not a solution. In that case you have create a 'configure' method which will be called in 'viewDidLoad'.

class HorizontalBarChart: UIView {

    private var presenter: HorizontalBarChartPresenter

    func configure(barHeight: CGFloat, spaceBetweenBars: CGFloat) {
        self.presenter = HorizontalBarChartPresenter(barHeight: barHeight, spaceBetweenBars: spaceBetweenBars)
    }
}

class CustomViewController: UIViewController {

    @IBOutlet weak var horizontalBarChart: HorizontalBarChart

    override func viewDidLoad() {
        super.viewDidLoad()
        horizontalBarChart.configure(barHeight: 100, spaceBetweenBars: 10)
    }
}

Upvotes: 0

Related Questions