我第一次在iOS应用程序中使用SpriteKit动画。我的目标是拖放标签,图像和文本字段。我使用SKLabelNode
和SKSpriteNode
为标签和图片完成了这项工作。
全球我宣布,
var deltaPoint = CGPointZero
var selectedNode = SKNode()
首先我用didMoveToView
方法创建了标签,图片,文本字段。然后将标签和图像添加为子节点,将textfield添加为子视图,如下面提到的代码。
let textField = UITextField(frame: CGRectMake(self.size.width / 2, self.size.height / 2 + 20, 200, 40))
textField.center = view.center
textField.borderStyle = .RoundedRect
textField.tag = 101
textField.textColor = UIColor.blackColor()
textField.font = UIFont.systemFontOfSize(17.0)
textField.placeholder = "Enter your name here"
textField.backgroundColor = UIColor.whiteColor()
textField.autocorrectionType = .Yes
textField.keyboardType = .Default
textField.clearButtonMode = .WhileEditing
textField.enabled = true
view.addSubview(textField)
let imageNode = SKSpriteNode(imageNamed: "images.jpg")
imageNode.name = kMovableImageNodeName
imageNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(imageNode)
let labelNode = SKLabelNode(fontNamed: "Helvetica")
labelNode.name = kMovableLabelNodeName
labelNode.text = "Welcome"
labelNode.fontSize = 30
labelNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(labelNode)
在TouchesBegan方法中,将触摸节点设置为所选节点。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
labelNode.zPosition = 0
imageNode.zPosition = 0
let positionInScene = touches.first?.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene!)
selectedNode = touchedNode
selectedNode.zPosition = 1
}
在TouchesMoved方法中,设置增量点值
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let currentPoint = touches.first?.locationInNode(self)
let previousPoint :CGPoint = (touches.first?.previousLocationInNode(self))!
deltaPoint = CGPointMake(currentPoint!.x - previousPoint.x, currentPoint!.y - previousPoint.y)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
selectedNode.zPosition = 1
deltaPoint = CGPointZero
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
selectedNode.zPosition = 0
deltaPoint = CGPointZero
}
在更新方法中,将新点设置为所选节点
override func update(currentTime: CFTimeInterval) {
let newPoint = CGPointMake(selectedNode.position.x + self.deltaPoint.x, self.selectedNode.position.y + self.deltaPoint.y)
selectedNode.position = newPoint
deltaPoint = CGPointZero
}
像这样如何拖放文本字段,当用户双击文本字段时,必须显示键盘。