Reputation: 433
I'm using UITextField for user to enter his name. And this is how I add UITextField to the game.
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)
later i unhide the textfield before it's needed. when I press on textfield in simulator the keyboard pops up. But when I press Return nothing happens.
I searched about this for sprite kit but found everything about uikit. I tried adding
func textFieldShouldReturn(_textField: UITextField) -> Bool {
self.view.endEditing(true); // or resignFirstResponder
return false;
}
to the GameViewController or in it's viewDidLoad or willLayoutSubviews but nothing worked. I can't understand how it would be done in sprite kit.
Any Help will be really Appreciated Thanks.
Upvotes: 0
Views: 73
Reputation: 318814
The line:
firstPlayer.delegate = self as? UITextFieldDelegate
should just be:
firstPlayer.delegate = self
The fact that you added the as? UITextFieldDelegate
probably means that you forgot to indicate that your class conforms to UITextFieldDelegate
.
Update your class declaration from something like:
class MyViewController: UIViewController {
to something like:
class MyViewController: UIViewController, UITextFieldDelegate {
Just add the , UITextFieldDelegate
to whatever your current declaration is.
You also have a typo on:
func textFieldShouldReturn(_textField: UITextField) -> Bool {
That needs to be:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
Note the space after the _
.
Upvotes: 2