swiftnscoder

What to use as NSCoder to initialize a View?


Hey guys I created a new custom View Class and now I want to build a instance of it, I initialized it with the following code:

required init?(coder aCoder: NSCoder) {
        super.init(coder: aCoder)
           tapRecognizer = UITapGestureRecognizer(
                           target: self, action: #selector(handleBarTap))
           addGestureRecognizer(tapRecognizer)
       }

       deinit {
           removeGestureRecognizer(tapRecognizer)
       }

And this is the instance, but what can I use as coder?

lazy var chartView = TutorialChartView(coder: )

Thanks in advance!


Solution

  • When you say View, do you mean UIView? The problem is that that's the wrong initializer. init(coder:) is not something you call; it's a process initiated by the storyboard when there is one of these things in the storyboard and you load that view controller.

    The code UIView designated initializer is init(frame:). Implement that and call it, and you're all set.

    (You may also have to provide an implementation of init(coder:) but it should just throw a fatalError, because you do not expect to be called this way.)