fs_tigre fs_tigre - 2 months ago 10
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

UIToolbar
when a
UITextField
is tapped using
inputAccessoryView
. 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
titleColor
,
frame
etc.

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]
toolBar.sizeToFit()

myTextField.inputAccessoryView = toolBar

Answer

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)
configure(button1)

// code for second button which is identical to the first button
let button2 = UIButton()
button2.setTitle("button2", forState: .Normal)
configure(button2)
Comments