Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : Error: 'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

Tags:

ios

swift

iphone

I have a problem when I build my app in swift 2. Xcode says:

'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

This is the code of the class :

class creerQuestionnaire: UIView {
  @IBOutlet weak var nomQuestionnaire: UITextField!
  @IBOutlet weak var question: UITextField!
  @IBOutlet weak var reponse: UITextField!
  var QR: Questionnaire

  @IBAction func creerQuestion(sender: AnyObject) {
    QR.ajouterQuestion(question.text!, nouvReponse: reponse.text!)
  }
}

and this is the class Questionnaire:

import Foundation

class Questionnaire {
  var QR = [String(), String()]

  func getQuestion(nbQuestion: Int) ->String {
    return QR[nbQuestion]
  }

  func getReponse(nbReponse: Int) ->String {
    return QR[nbReponse]
  }

  func ajouterQuestion(nouvQuestion: String, nouvReponse: String) {
    QR += [nouvQuestion, nouvReponse]
  }
}

Merci!

like image 880
R1' Avatar asked Feb 07 '16 15:02

R1'


2 Answers

Note for required: Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer.

Note for override: You always write the override modifier when overriding a superclass designated initializer, even if your subclass’s implementation of the initializer is a convenience initializer.

Above both notes are referred from: Swift Programming Language/Initialization

Therefore, your subclass of UIView should look similar to the sample below:

class MyView: UIView {
    ...
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    ...
}
like image 132
Allen Avatar answered Sep 20 '22 15:09

Allen


According to the latest swift syntax, the init method needs to add methods:

required init?(coder aDecoder: NSCoder) 
{
         fatalError("init(coder:) has not been implemented")
}
like image 33
Chenghui He Avatar answered Sep 19 '22 15:09

Chenghui He