Reputation: 4632
I have below code to create a custom IBDesignable UIButton. Note that I do not have any IBInspectables since I do not need any. I want all my custom buttons to be same.
import UIKit
@IBDesignable class ShButton: UIButton {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
self._setup()
}
override func awakeFromNib() {
self._setup()
}
override func prepareForInterfaceBuilder() {
self._setup()
}
private func _setup(){
self.layer.cornerRadius = 5.0
self.layer.masksToBounds = true
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 1.0
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
deinit {
}
}
There are two problems:
Upvotes: 1
Views: 829
Reputation: 773
I'm still kind of an iOS newb, but I had a similar situation, and this worked fine for me:
@IBDesignable class ShButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
self._setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self._setup()
}
private func _setup(){
self.layer.cornerRadius = 5.0
self.layer.masksToBounds = true
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 1.0
self.setNeedsDisplay()
}
}
This allowed me to set a default cornerRadius
on a button without having to use an IBInspectable
, and worked in both the storyboard and at runtime.
EDIT: Updated answer
Upvotes: 1