Reputation: 43
I've searched endlessly for a solution to this. Many of the questions already opened are either not answered or very vague in explanation.
I am trying to add a UITextField to my SKScene as players need to be able to create an account for this game.
var txtField:UITextField!
Here I declare the text field.
txtField = UITextField(frame: CGRect(x: frame.midX, y: frame.midY, width: 200, height: 30));
view.addSubview(txtField!)
With these two lines I'm trying to add the text field as a subview. When I run the app, the text field is not visible. What am I doing wrong here? Do I need to change the zPosition of this subview?
Would really appreciate some help on this! :)
Upvotes: 4
Views: 2716
Reputation: 1086
I recently came up with two functions that can help here for the future.
func createTextField (at: CGPoint, size: CGSize, isSecure: Bool = false) -> NSTextField {
var newSize = size
newSize.width *= (self.view?.frame.width)! / self.frame.width
newSize.height *= (self.view?.frame.height)! / self.frame.height
var pos = convertPoint(toView: at)
pos.x -= (newSize.width / 2)
pos.y -= (newSize.height / 2)
return !isSecure ? NSTextField (frame: NSRect (x: pos.x, y: pos.y, width: newSize.width, height: newSize.height)) : NSSecureTextField (frame: NSRect (x: pos.x, y: pos.y, width: newSize.width, height: newSize.height))
}
func createTextField (spriteNamed: String, isSecure: Bool = false) -> NSTextField {
let node = self.childNode(withName: spriteNamed) as! SKSpriteNode
let pos = convert(node.position, from: node.parent!)
node.removeFromParent()
return createTextField(at: pos, size: node.size, isSecure: isSecure)
}
These functions allow you to add a ordinary SKSpriteNode to your Scene and have them be replaced by NSTextFields.
Upvotes: 0
Reputation: 10105
If you want to add a UITextField
onto the scene, be sure to call addSubview
with the visible SKView
, you may check the following code:
import SpriteKit
import PlaygroundSupport
let sceneFrame = CGRect(origin: .zero, size: CGSize(width: 200, height: 200))
var scene = SKScene(size: sceneFrame.size)
scene.backgroundColor = UIColor.lightGray
let textFieldFrame = CGRect(origin: .zero, size: CGSize(width: 200, height: 30))
let textField = UITextField(frame: textFieldFrame)
textField.backgroundColor = UIColor.white
textField.placeholder = "hello world"
let skView = SKView(frame: sceneFrame)
skView.addSubview(textField)
skView.presentScene(scene)
PlaygroundPage.current.liveView = skView
the result is:
Upvotes: 3