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)
    }
}
3
  • See stackoverflow.com/q/38386339/3141234 and developer.apple.com/documentation/foundation/nscoding Commented Sep 1, 2019 at 19:33
  • There are lots of solutions depending on whether you ever will in fact init from storyboard. Commented Sep 1, 2019 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... Commented Sep 1, 2019 at 20:25

1 Answer 1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.