如何在 Sprite 套件中隐藏 return 键上的键盘?

How to hide keyboard on return key in Sprite kit?

我正在使用 UITextField 让用户输入他的名字。这就是我将 UITextField 添加到游戏中的方式。

let firstPlayer:UITextField = UITextField()
firstPlayer.frame = CGRect(origin: CGPoint(x: (self.scene?.size.width)! * 0.21, y: (self.scene?.size.height)! * 0.2), size: CGSize(width: 200, height: 30))
firstPlayer.placeholder = "First Player Name"
firstPlayer.backgroundColor = UIColor.lightGray
firstPlayer.autocorrectionType = UITextAutocorrectionType.no
firstPlayer.keyboardType = UIKeyboardType.default
firstPlayer.keyboardAppearance = UIKeyboardAppearance.default
firstPlayer.delegate = self as? UITextFieldDelegate
firstPlayer.isHidden = true
view.addSubview(firstPlayer)

稍后我在需要它之前取消隐藏文本字段。当我在模拟器中按下文本字段时,键盘会弹出。但是当我按下 Return 时没有任何反应。

我搜索了 sprite kit,但找到了关于 uikit 的所有信息。我尝试添加

    func textFieldShouldReturn(_textField: UITextField) -> Bool {
      self.view.endEditing(true);   // or resignFirstResponder
      return false;
    }

到 GameViewController 或在它的 viewDidLoad 或 willLayoutSubviews 中,但没有任何效果。 我不明白在 sprite kit 中是怎么做到的。

非常感谢任何帮助。

行:

firstPlayer.delegate = self as? UITextFieldDelegate

应该是:

firstPlayer.delegate = self

您添加 as? UITextFieldDelegate 的事实可能意味着您忘记指出您的 class 符合 UITextFieldDelegate.

更新您的 class 声明,例如:

class MyViewController: UIViewController {

类似于:

class MyViewController: UIViewController, UITextFieldDelegate {

只需将 , UITextFieldDelegate 添加到您当前的声明中即可。

您还有一个错字:

func textFieldShouldReturn(_textField: UITextField) -> Bool {

需要:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

注意 _ 之后的 space。