非常基本的 Swift 动画
Posted
技术标签:
【中文标题】非常基本的 Swift 动画【英文标题】:Very Basic Swift Animation 【发布时间】:2015-08-14 22:22:56 【问题描述】:我正在尝试将视图从情节提要上的位置向上移动 100 像素。
如果随机生成的数字为 1,则标签变为未中奖。
如果随机生成的数字是 2,则标签会更改为他们中奖了。
我正在使用以下代码:
override func motionEnded(motion: UIEventSubtype,
withEvent event: UIEvent?)
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
UIView.animateWithDuration(3.0, animations:
self.stampView.frame = CGRectMake(xPosition, yPosition, height, width)
)
print("SHAKEN!")
我发现有时当我摇动设备时,动画会从原始位置下方 100px 开始并移回原位,而其他时候它会从最后一个位置向上移动 100px。
如何确保它始终从故事板上的原始位置移动?
【问题讨论】:
你在使用自动布局吗? 嗨,不,我发现如果我将文本更改移出功能,它似乎工作得非常愉快。不知道为什么! 可能在后台线程上执行了“motionEnded”。尝试将您的代码包装在主队列中。 让我知道这是否有效。 【参考方案1】:确保某物留在同一位置的最佳方法是在您的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!")
无论如何,我希望对您有所帮助,如果您还有其他问题,欢迎您提出。
【讨论】:
以上是关于非常基本的 Swift 动画的主要内容,如果未能解决你的问题,请参考以下文章
在 swift Playground 中创建纹理动画 [关闭]