Swift UIButton单击时未突出显示或运行代码

Swift UIButton单击时未突出显示或运行代码,swift,uibutton,Swift,Uibutton,我正在设置26个按钮,将它们作为子视图添加到letterButtonLabel,并将它们附加到letterButtons数组 for row in 0..<6 { for column in 0..<5 { if row == 5 && column > 0 { continue } let letterButton = UIButton(type: .system)

我正在设置26个按钮,将它们作为子视图添加到letterButtonLabel,并将它们附加到letterButtons数组

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)
            }
        }
var index = 0

        for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
             letterButtons[index].setTitle("\(letter)", for: .normal)
             index += 1
        }
然后手动添加布局约束

以下是每个按钮的功能:

@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)
        }
    }

添加所有内容以防万一

我的按钮没有突出显示或单击。这里有什么可以解释这个问题的吗?我对常见错误很好奇。

UILabel默认情况下有userInteractionEnabled=false。
将此设置为true应该可以解决您的问题

如果您将普通UIView用作父视图而不是标签,是否有效?试图消除可能性。@PhillipMills啊,是的!我没有意识到我不能将其添加到标签中,但这是一个完美的常识。我将标签更改为UIView,效果很好。非常感谢。将这些添加到UIView而不是UILabel是更好的做法吗?我实际上并不需要标签的功能,也没有意识到我应该使用更好的方法。是的,如果你不需要标签的功能,一个简单的UIView会更干净。