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

问题描述 投票:0回答:1

我正在设置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)
            }
        }

然后,我使用letterButtons数组为每个按钮分配一个字母。

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

(添加所有以防万一)

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

swift uibutton
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.