Search code examples
iosswiftuibuttontags

how to find index of UIButton in array if they are the same value?


sorry if the title not describe the problem well i have 4 button with 4 letters ["g","o","o","d"] it is a game about if the player can guess the word , which is in this case the word is : "good"

i have a hint button that do this : *give one letter from the four *hide the button with the given letter it works very well

but the problem is : the word "good" has two "o" letter so the hint button now well delete two button with the letter "O"

here is what i did so far :

//  this method will add a letter from the right word "qlap" to the answer textfield and it work perfectly :
    
let text_ans = ans.text?.count
ans.text! += qlab![text_ans!+0]
    
// the four letters
let buttin = [Letter1,Letter2,Letter3,Letter4]

// check if hint letter above == button title letter
for title in buttin {
    if qlab![text_ans!+0] == title!.title(for: .normal) {
        let tag = title!.tag
        if title?.tag == tag {
            // how can i just hide for once if there is a duplicate
            title?.isHidden = true
        }
    }
}

and here is a gif to make it more clear :

see the gif

i tried do it with the button tags rather than title but at the end i went to the same result


Solution

  • You could use the first(where:) (documented here) function to find the first button with a title that matches what you are looking for and where isHidden == false.

    So something along the lines of:

    if let hintButton = buttin.first(where: { $0.title(for: .normal) == qlab![text_ans!+0] && !$0.isHidden }) {
        // now you have the first - not hidden - button matching what you are looking for, time to hide it
        hintButton.isHidden = true
    }
    

    note: I haven't checked the above in a compiler so there might be syntax errors which I'm sure the compiler will inform you about in it's friendly manner.