-1

I want to pass an Int to a function so I can change the background color of the right UIButton

Example:

@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!


changeBackground(1);

func changeBackground(number:Int){

button(number).backgroundColor = UIColor.redColor()


}
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

You can add a tag for each Button in interface Builder, or create an Array containing your Buttons. Then you pass the index of the button you want to update to your function.

Edit:

Instead of passing in a number it probably would be better to pass in the button itself. This way you can re-use the method more easily.

smnk
  • 471
  • 1
  • 6
  • 25
0

I would have done it differently. Create a global variable e.g.:

var buttonColor: Int = 0

and do a switch statement or if-else so that when:

switch(buttonColor):
case 1:
 //set color here
case 2:
 //set color here

also this can help further to know which button to be changed since UI components have storyboard ID:

Get button pressed id on Swift via sender

Community
  • 1
  • 1
ksa_coder
  • 1,393
  • 3
  • 15
  • 38