Reputation: 231
I'm setting up 26 buttons, adding them as subviews to a letterButtonLabel, and appending them to an letterButtons array.
for row in 0..<6 {
for column in 0..<5 {
if row == 5 && column > 0 { continue }
let letterButton = UIButton(type: .system)
letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36)
letterButton.setTitle("O", for: .normal)
letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)
let frame = CGRect(x: width * column, y: height * row, width: width, height: height)
letterButton.frame = frame
letterButtonLabel.addSubview(letterButton)
letterButtons.append(letterButton)
}
}
Afterwards, I assign a letter to each button using the letterButtons array.
var index = 0
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
letterButtons[index].setTitle("\(letter)", for: .normal)
index += 1
}
I then manually add layout constraints.
Here is the functionality for each button:
@objc func letterTapped(_ sender: UIButton) {
// check the letter and react
sender.isHidden = true
guard let word = currentWord else { return }
guard var charactersArray = currentWordField.text?.components(separatedBy: "") else { return }
guard let originalCurrentWordField = currentWordField.text else { return }
for (index, letter) in word.enumerated() {
let strLetter = String(letter)
if strLetter == sender.titleLabel?.text {
charactersArray[index] = strLetter
}
}
currentWordField.text = charactersArray.joined()
if currentWordField.text == originalCurrentWordField {
livesLeft -= 1
}
if wordBank.contains(word) {
// you got it! reset letters
level += 1
let ac = UIAlertController(title: "Good job!", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Continue", style: .default, handler: resetForNextLevel)
ac.addAction(action)
present(ac, animated: true)
}
if livesLeft == 0 {
let ac = UIAlertController(title: "Game Over", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Restart", style: .default, handler: resetForNextLevel)
ac.addAction(action)
present(ac, animated: true)
}
}
(adding all just in case)
My button doesn't highlight or click. Is there anything here that might explain the problem? I'm curious about common mistakes.
Upvotes: 0
Views: 23
Reputation: 1203
UILabel has by default userInteractionEnabled = false
.
Setting this to true
should fix your problem
Upvotes: 1