0

I have created a custom UIView with .xib and now trying to display it through init method but I get strange Thread 1: Fatal error: init(coder:) has not been implemented error. 1. So, I have created UIView xib and swift file:

override init(frame: CGRect) {
    super.init(frame: frame)

    createSubview()
}

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

func createSubview() {
    let newFormView = UINib(nibName: String(describing: NewProfileFormView.self), bundle: nil).instantiate(withOwner: self, options: nil).first as! NewProfileFormView
    self.addSubview(newFormView)
}

and call it from another ViewController as:

let newProfileViewController = UIViewController()
let newFormView = NewProfileFormView()

newProfileViewController.view = newFormView
self.navigationController?.pushViewController(newProfileViewController, animated: true)

but it crashes with above mentioned error. Could you please help me to find my mistake?

J. Doe
  • 521
  • 4
  • 15
  • Your mistake is saying "crash me": that is what `fatalError` means. What you need to do is provide a _meaningful_ implementation of `init(coder:)`, because it is the initializer that _will in fact be called_ when the view comes from the _xib_ file. Here is an example of a meaningful implementation: https://stackoverflow.com/a/32697956/341994 – matt Apr 29 '18 at 14:02
  • @matt but I'm NOT telling it to crash. The second `init` method with crash `HAS TO BE ADDED`, as it's required by the IDE. – J. Doe Apr 29 '18 at 14:04
  • No. The `init(coder:)` implementation is required because you implement `init(frame:)`, but the crash is not. _You_ are the one telling it to crash. — You are making _two_ mistakes. You don't need the `init(frame:)` implementation, and you _do_ need the `init(coder:)` implementation but you need it to be _meaningful_. — It _is_ a duplicate. The duplicate marking means "Your question has been answered already on SO." It _has_ been answered, many times. I could give you lots more instances. – matt Apr 29 '18 at 14:04
  • @matt oh, calling `super.init(coder: aDecoder)` in it fixed the problem! I think I have to read about `initialisators` a litle bit more. Thanks! – J. Doe Apr 29 '18 at 14:07
  • 1
    And please, next time, don't be so quick to push back against the duplicate closure. Remember, the reason you are having trouble is that there is something you don't know. You need to listen to the help you are being given. – matt Apr 29 '18 at 14:08

0 Answers0