Subclassing UIButton: Which approach is better?

Hi,

Here are two subclasses for two different buttons. Both seem to do the job okay, but as you can see, they are very different in the code. I’m wondering which is the better option? Does it matter either way, or is there a third option that might be better still? My aim is to put all my button code into a single class. Here are the two subclasses:
1.
class SymbolButton: UIButton {

override func layoutSubviews() {
self.layer.cornerRadius = 8.0
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.white.cgColor
self.titleLabel?.text = “Symbol”
self.setTitleColor(.white, for: .normal)
self.frame.size.width = 80
self.titleLabel?.frame.size.width = 80
self.titleLabel?.textAlignment = .center
}

class RoundedButton: UIButton {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
createButton()
}

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

self.frame.size.height = 150

}

private func createButton(){
//Define Layer
self.layer.cornerRadius = 8.0
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.lightGray.cgColor
//self.backgroundColor = UIColor(hex: “#96AAD4FF”)
self.backgroundColor = Colors.shared.bgColor
self.setTitleColor(.white, for: .normal)
}
}

1 basically changes how the button looks during layout phase of the subviews

while 2 changes the look of the button during initialization, 2 should be the better option since it starts at initialization, you can then use layout subviews later on when you want to add additional “looks” to the button

Thanks. So there is nothing inherently wrong with the first option? In regards to the second option: if the button is already in place using the storyboard, then there is no need to initialise the button? What is the criteria for deciding one or the other?

yes if the button is already in the storyboard it means it has initialized (or will be initialized on launch) usually its the size and position that is automatically created for you, so its a good idea to just change the style (layout subviews) once initialize is over

you have to create an IBOutlet for this though

Thanks. I have the IBOutlet. I have the two different approaches thanks to randomly searching Dr. Google for solutions to problems. I’m was going through the code looking to tidy it up a bit when I came across the two classes. I don’t actually need to initialise a button so I’ll just move it all into one class, and as you say, just override the layout subviews.

1 Like