【问题标题】:How to hide keyboard on return key in Sprite kit?如何在 Sprite 套件中的返回键上隐藏键盘?
【发布时间】:2020-01-10 02:32:15
【问题描述】:

我正在使用 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 中完成。

任何帮助都会非常感谢。

【问题讨论】:

  • textFieldShouldReturn 被调用了吗?
  • @rmaddy 是的,这就是我不明白我怎么能在精灵套件中调用它我们不能使用节点触摸或类似的东西
  • 我认为您没有回答我的问题。如果你在textFieldShouldReturn 里面放了一个断点,然后敲回车键,textFieldShouldReturn 是停在断点处吗?是还是不是?
  • @rmaddy 不,它不会打印任何东西
  • 那么textFieldShouldReturn是sprite kit中关闭键盘的方法吗?

标签: swift sprite-kit keyboard uitextfield


【解决方案1】:

行:

firstPlayer.delegate = self as? UITextFieldDelegate

应该是:

firstPlayer.delegate = self

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

从以下内容更新您的类声明:

class MyViewController: UIViewController {

类似于:

class MyViewController: UIViewController, UITextFieldDelegate {

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

你还有一个错字:

func textFieldShouldReturn(_textField: UITextField) -> Bool {

必须是:

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

注意_后面的空格。

【讨论】:

  • 以前当我尝试将委托设置为 self 时,它曾经给我这个错误 Cannot assign value of type 'HomeScene' to type 'UITextFieldDelegate?'
  • 是的,这就是我回答中的第二个更改所解决的问题。阅读我的全部答案并进行所有三个更改。
  • 但是在将委托添加到类之后现在它没有给我那个错误,但它仍然没有隐藏键盘
  • 您是否还解决了我在回答中指出的第三个错误?
  • 还要确保textFieldShouldReturn 是该类的顶级方法,而不是在任何其他方法中。
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2014-12-26
  • 2011-12-13
  • 2010-11-19
相关资源
最近更新 更多