1

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)
    }
}
achntrl
  • 23
  • 2
  • See https://stackoverflow.com/q/38386339/3141234 and https://developer.apple.com/documentation/foundation/nscoding – Alexander Sep 01 '19 at 19:33
  • There are lots of solutions depending on whether you ever will in fact init from storyboard. – matt Sep 01 '19 at 20:13
  • I managed to create it programmatically by deleting the "super.init(coder)" and remplace it with fatalError("NSCoding not supported") but at first I wanted to create my view directly in my storyboard but I can't manage to do it... – achntrl Sep 01 '19 at 20:25

1 Answers1

0

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)
    }
}
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93