fs_tigre fs_tigre - 1 year ago 72
iOS Question

What is the best way to reuse the attributes from a UIButton in Swift

I have a bunch of buttons that I'm adding to a

when a
is tapped using
. All of these buttons are identical except for the title and what I would like to be able to do is reuse the UI attributes such as

What would be the most efficient way to accomplish what I described above?

Here is the code...

// code for first button
let button1 = UIButton();
button1.backgroundColor = UIColor.orangeColor()
button1.setTitle("button1", forState: .Normal)
button1.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button1.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
button1.frame = CGRect(x:0, y:0, width:35, height:35)
button1.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)

// code for second button which is identical to the first button
let button2 = UIButton();
button2.backgroundColor = UIColor.orangeColor()
button2.setTitle("button2", forState: .Normal)
button2.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button2.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
button2.frame = CGRect(x:0, y:0, width:35, height:35)
button2.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)

let barButton = UIBarButtonItem()
barButton.customView = button

let barButton2 = UIBarButtonItem()
barButton2.customView = button2

let toolBar = UIToolbar()
toolBar.items = [ barButton, barButton2]

myTextField.inputAccessoryView = toolBar

Answer Source

Refactor the duplicate code into a single local function.

func configure(_ button:UIButton) {
    button.backgroundColor = UIColor.orangeColor()
    button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    button.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
    button.frame = CGRect(x:0, y:0, width:35, height:35)
    button.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)

// code for first button
let button1 = UIButton()
button1.setTitle("button1", forState: .Normal)

// code for second button which is identical to the first button
let button2 = UIButton()
button2.setTitle("button2", forState: .Normal)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download