0
@IBOutlet var buttons: [UIButton]!
@IBOutlet var labels: [UILabel]!

@IBAction func cevapSeçildi(_ sender: UIButton) {
    if sender == buttons[0] {
        `enter code here`
        labels[0].backgroundColor = UIColor.yellow 
    }
}

I want this ..

var x : Int

if sender == buttons[x] { labels[x].backgroundColor = UIColor.yellow }

can you help me please

LGP
  • 4,135
  • 1
  • 22
  • 34
Samm Hadji
  • 15
  • 7
  • there are lots of buttons and I want to change the label's background color next to button. I can make it one by one in the collection array. but can I make it programmatically – Samm Hadji Mar 24 '18 at 22:33

2 Answers2

0

You can get the index of the button with

var index = buttons.index(of: sender)

then set

labels[index].backgroundColor = UIColor.yellow

If you would like to set all the other buttons to a different color at the same time, consider this:

let buttonIndex = buttons.index(of: sender)
for var label in labels {
    if(labels.index(of: label) == buttonIndex) {
        label.backgroundColor = UIColor.yellow
    } else {
        label.backgroundColor = UIColor.white
    }
}
dktaylor
  • 874
  • 7
  • 12
0

A couple of points:

  1. Using your array of buttons to map to cell indexes will only work for a single-section table view or collection view. If you have a sectioned table view or a collection view that's in rows and columns then that approach won't work.

  2. If you want to make the label yellow on the selected cell but white for all others, it doesn't make sense to change ALL the cells. A table view/collection view only shows a few cells at a time, and as you scroll, the cells get recycled and used for different indexes in your table view/collection view.

If you let me know whether you're using a table view or a collection view I can show you a better way to do this.

EDIT:

Since you're not using a table view or collection view, it does make sense to manipulate the labels directly:

@IBAction func cevapSeçildi(_ sender: UIButton) {
    let buttonIndex = buttons.index(of: sender)
    for (index, label) in labels.enumerated) {
    }
    if index == buttonIndex {
        label.backgroundColor = UIColor.yellow 
    } else {
        label.backgroundColor = UIColor.white
    } 
}
Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks for response. Not table view. Just buttons and labels side by side embed in a stack. İ want to change others because there is only one correct answer. İf the user changes the answer i want others to be white – Samm Hadji Mar 25 '18 at 13:54
  • Why did you refer to an indexPath then? That's a structure used to reference cells in Table views and collection views. – Duncan C Mar 25 '18 at 20:55
  • thanks for all your help. I am very new new to coding. so sometimes I can't figure out things that is very easy for you :) – Samm Hadji Mar 26 '18 at 06:51