2

Ive been hitting a roadblock with NSCoding. Specifically, instantiating a class that conforms to NSCoding. Maybe I'm missing something really obvious, but I haven't found any answers yet.

```swift

class TitleTextField: UITextField, UITextFieldDelegate {



required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

    font = UIFont(name: "Helvetica-Neue", size: 25)

}

```

This is just one example, a simple one. When I try to instantiate this class elsewhere, i.e something like "let textField = TitleTextField()" (sorry can't figure out how to format that) I get the error "missing argument for parameter 'coder' in call". When I try to fix it with the suggested TitleTextField(coder: NSCoder) it throws an error and tells me to delete "coder:", then it throws another error and says "Cannot convert value of type '(NSCoder).Type' (aka 'NSCoder.Type') to expected argument type 'NSCoder'"

How do I instantiate this class?

This gave me trouble on a custom class I created that conformed to NSCoding as well after following several different examples to a T.

R.P. Carson
  • 439
  • 5
  • 20

2 Answers2

2

That's really simple - you need to add another designated initializer, typically init(frame:) for UIView. You can actually just call super.init(...) in it.

The problem is that once you add one initializer, the other initializers stop being inherited from superclass and you have to define them.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    font = UIFont(name: "Helvetica-Neue", size: 25)
}

This code worked for me. Seems you missed optional in func declaration

public class UIView : UIResponder {
    public init?(coder aDecoder: NSCoder)
}
ale_stro
  • 806
  • 10
  • 23
  • I dont understand what UIView has to do with it. And the code compiles, I just cant make an instance of TitleTextField – R.P. Carson Mar 19 '16 at 16:31
  • It was just code copy-paste from the UIView interface to show the `required init` implementation. – ale_stro Mar 21 '16 at 18:52