我正在尝试将其在故事板上的位置向上移动100px。
如果随机生成的数字为1,则标签会更改为表示尚未获胜。
如果随机生成的数字是2,则标签会改变,表示他们已经赢了一个镜头。
我使用以下代码:
./true
我发现有时当我摇动设备时,动画开始于原始位置以下100px并移回原位置,有时它会从最后位置向上移动100px。
如何确保它始终从故事板上的原始位置移动?
答案 0 :(得分:2)
确保某些内容位于同一位置的最佳方法是在Main.storyboard
文件中为其提供约束(首先要做的事情)。另外,作为额外的预防措施,您可以在viewDidLoad
中阅读其帧值并在motionEnded
中重新设置。
var stampFrame : CGRect = CGRect(x: 0, y: 0, width: 0, height: 0) // This is stampFrame's initial value before being set in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
stampFrame = stampView.frame // Here we store the frame value for usage later
// If you would like, you can also set this in a method like viewWillAppear or viewDidAppear, but I'd just keep it in viewDidLoad
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
stampView.frame = stampFrame
if motion == .MotionShake{
let randomNumber = arc4random_uniform(2) + 1
print(randomNumber)
if randomNumber == 1 {
labelOne.text = "Sorry!"
labelTwo.text = "You Have Not Won This Time"
labelThree.text = "Better Luck Tomorrow"
}
if randomNumber == 2 {
labelOne.text = "Winner!"
labelTwo.text = "1 x Shot Patron Cafe"
labelThree.text = "Show at the bar to claim."
}
// let xPosition = stampView.frame.origin.x
// View will slide 20px up
// let yPosition = stampView.frame.origin.y - 100
// let height = stampView.frame.size.height
// let width = stampView.frame.size.width
// The code above is redundant, we can just do it all in the UIView.animate
UIView.animate(withDuration: 3.0, animations: {
self.stampView.frame.origin.y -= 100
// This moves stampView's position up 100pts from its current location
})
print("SHAKEN!")
}
好吧无论如何,我希望如果您有任何疑问,请帮助您,欢迎您的询问。