Geeroz Geeroz - 5 months ago 23
iOS Question

Add Custom UIButton Programmatically fatal error

I'm creating a custom round UIButton with following code. I want to add this UIButton programmatically. iOS crashed when I try to do that. It work fine in InterfaceBuilder.

Xcode give me this error.


fatal error: init(coder:) has not been implemented:


What should I do to fix it? Any suggestion would be really appreciate.

Here is the code that I use for Round UIButton.

import UIKit

@IBDesignable
class RoundButton: UIButton {

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

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

initWithCoder
override func awakeFromNib() {
setupView()
}

override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}

func setupView() {
let radius = self.frame.size.height / 2
layer.cornerRadius = radius
}

}

Answer

If it were me, I'd avoid the initializers altogether:

import UIKit

@IBDesignable
class RoundButton: UIButton {

    override func awakeFromNib() {
        setupView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setupView()
    }

    func setupView() {
        let radius = self.frame.size.height / 2
        layer.cornerRadius = radius
    }
}

Something like that should work. You call setupView from awakeFromNib so I don't think there is any need to call it from inside the initializers.

If there is a reason why you need to write your own version of init(coder:), then something as simple as this may work:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupView()
}