我目前的代码在
之下 class SetupScene: SKScene{
let myTextField: UITextField = UITextField(frame: CGRect(x: 208, y: 175, width: 230.00, height: 33.00));
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "pixelBackground")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.size = self.size
background.zPosition = -10
self.addChild(background)
self.view?.addSubview(myTextField)
myTextField.backgroundColor = UIColor.white
myTextField.text = "Enter your name:"
myTextField.borderStyle = UITextBorderStyle.line
myTextField.textAlignment = .center
myTextField.font = UIFont(name: "04b_25", size: 25)
}
}
上面的代码myTextField位于我屏幕的左上角(我的屏幕是横向)。我可以手动将它移动到我想要的位置,方法是将数字输入x和y值,然后根据设备移动到不同的位置。当我尝试做的时候:
myTextField = UITextField(frame: CGRect(x: self.size.width/2, y: self.size.height/2, width: 230.00, height: 33.00))
屏幕上缺少myTextField。我怎样才能像SpriteKit中的所有设备那样居中:(x:self.size.width / 2,y:self.size.height / 2)
*注意我想以编程方式执行此操作而不是使用Storyboards
答案 0 :(得分:1)
不要使用框架。使用AutoLayout。
将视图(文本字段)上的translatesAutoresizingMaskIntoConstraints
设置为false,然后使用X轴NSLayoutAnchor
和Y轴NSLayoutAnchor
使视图的中心等于它的中心是超级视图。
答案 1 :(得分:1)
创建自定义类,并在需要时全局使用它。
class CustomTextField: UITextField {
override init (frame : CGRect) {
super.init(frame : frame)
}
func setUp() {
//Setting constraints of CustomTextField with centerX, centerY
self.translatesAutoresizingMaskIntoConstraints = false
self.centerYAnchor.constraint(equalTo: (self.superview?.centerYAnchor)!).isActive = true
self.centerXAnchor.constraint(equalTo: (self.superview?.centerXAnchor)!).isActive = true
//use if you want fixed width
self.widthAnchor.constraint(equalToConstant: 250).isActive = true
//self.heightAnchor.constraint(equalToConstant: 250).isActive = true
self.backgroundColor = .red
self.textAlignment = .center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController{
var demoText = CustomTextField()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(demoText)
demoText.setUp()
demoText.text = "hello"
}
}
输出: