Alexey Shvachka
Alexey Shvachka

Reputation: 243

Best way to let multiple UIButtons share the same appearance

What is the best practice to let multiple buttons share the same appearance?

Right now I'm creating those buttons in a loop like this:

for i in 0..<10{
    let button = UIButton()
    button.setTitle(String(i), for: .normal)
    button.backgroundColor = #colorLiteral(red: 0.3137254902, green: 0.2745098039, blue: 0.2745098039, alpha: 0.5977632705)
    numberButtons.append(button)
    button.layer.borderColor = #colorLiteral(red: 0.04296875, green: 0.04296875, blue: 0.04296875, alpha: 0.5).cgColor
    button.layer.borderWidth = 1.0
    button.addTarget(self, action:  #selector(buttonAction), for: .touchUpInside)
}

What is Swift way to do such things? Subclass UIButton? Or add some initialising method as extension?

Upvotes: 0

Views: 113

Answers (1)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

1- Create a subclass of UIButton.

2- Put all your customizations in its constructor.

3- Use it for your buttons (in your storyboard or in code).

The discussion in this answer will help you subclass UIButton and customize it in the way you want.

And this answer provides a general rule of thumb on when to use extensions and when to use inheritance.

Upvotes: 2

Related Questions