1

I have 5 buttons within a UIStackView, and I want to find out which index is being selected, and later compare those indexes. My code right now gives me an Array.Index. I've tried both subviews and arrangedSubviews. Is there anyway I can turn this into an Integer? I can't figure it out. Thanks!!

if let selectedIndex = stackview.subviews.index(of: sender) {

}

// UPDATE I kinda got what I wanted with:

let int = stackview.subviews.distance(from: stackview.subviews.startIndex, to: selectedIndex)

I'm still not sure if this is the most efficient way, but it does the job for now.

robinyapockets
  • 363
  • 5
  • 21

3 Answers3

5

enter image description here

index(of:) return Int.

Also you should find your button in the arrangedSubviews, not in the subviews

Ryan
  • 4,799
  • 1
  • 29
  • 56
1

Assuming your stack view contains only buttons, and each button is connected to this @IBAction, this should work:

@IBAction func didTap(_ sender: Any) {

    // make sure the sender is a button
    guard let btn = sender as? UIButton else { return }

    // make sure the button's superview is a stack view
    guard let stack = btn.superview as? UIStackView else { return }

    // get the array of arranged subviews
    let theArray = stack.arrangedSubviews

    get the "index" of the tapped button
    if let idx = theArray.index(of: btn) {
        print(idx)
    } else {
        print("Should never fail...")
    }

}
DonMag
  • 69,424
  • 5
  • 50
  • 86
0

I would add a tag to each of your buttons (button.tag = index) then check the tag of your sender.

So then you can wire up each of your buttons to the same function with a sender parameter, then check if sender.tag == index.

Adam Zarn
  • 1,868
  • 1
  • 16
  • 42