Andreas
Andreas

Reputation: 462

Combine layer styles to multiple UIButton in Swift

I have these 4 lines to append a shadow to a UIButton:

option1Label.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
option1Label.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
option1Label.layer.shadowOpacity = 1.0
option1Label.layer.shadowRadius = 3.0

But I also have 4 different buttons, which would result in repeating myself for every button and just change the number in option1Label.

Maybe a dumb example, but in CSS it would look like this to apply the same style to multiple elements:

.element1,
.element2,
.element3 {
    color: #121212;
}

Is there any way in Swift 4 to combine these 4 buttons and apply them all at once to these 4 lines of styles?

UPDATE:

A bit more code to see what's going on. The 4 buttons are also IBOutlets, because they need to change the text at some point:

@IBOutlet weak var option1Label: UIButton!
@IBOutlet weak var option2Label: UIButton!
@IBOutlet weak var option3Label: UIButton!
@IBOutlet weak var option4Label: UIButton!

IBAction:

@IBAction func answerButton(_ sender: UIButton) {
    pickedAnswer = sender.tag
    questionNumber += 1
}

Upvotes: 0

Views: 412

Answers (1)

André Slotta
André Slotta

Reputation: 14030

You could either subclass UIButton and add the shadow there or do something like this:

let option1Label = UIButton()
let option2Label = UIButton()
let option3Label = UIButton()
let option4Label = UIButton()

[option1Label, option2Label, option3Label, option4Label].forEach { button in
    button.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
    button.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
    button.layer.shadowOpacity = 1.0
    button.layer.shadowRadius = 3.0
}

The label / button naming confuses me btw... :)

Upvotes: 3

Related Questions