-1

I have a subclass of UIButton and when I add the button to my view controller in my storyboard, my app crashes with fatalError("init(coder:) has not been implemented"). If I manually add the subclassed button in code it works fine. What am I doing wrong?

import UIKit

class RAPanicButton: UIButton {

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

        self.layer.cornerRadius = self.frame.height / 2
        self.layer.masksToBounds = true
        self.clipsToBounds = true

        self.backgroundColor = .red
        self.setTitle("Panic!", for: .normal)
        self.titleLabel?.textColor = .white
    }

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

enter image description here

raginggoat
  • 3,570
  • 10
  • 48
  • 108

1 Answers1

4

Stuff from the storyboard will be initialised by calling the init(coder:) initialiser. This means that if you want to use your view in the storyboard, you must not throw a fatalError in init(coder:).

You can put the same code in both initialisers:

func setup() {
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = true
    self.clipsToBounds = true

    self.backgroundColor = .red
    self.setTitle("Panic!", for: .normal)
    self.titleLabel?.textColor = .white
}

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

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313