Ant*_*omi 1 animation uiview ios swift
我试图用一个按钮停止一个在视图中上下动画的方形(在循环中上下)并读取位置(x,y)这是该动作的代码
override func viewDidLoad() {
super.viewDidLoad()
while buttonPress == false {
movement()
}
}
func movement() {
coloredSquare.backgroundColor = UIColor.blueColor()
coloredSquare.frame = CGRect(x:0, y:500, width:50, height:50)
self.view.addSubview(coloredSquare)
movementDown()
}
func movementDown() {
// lets set the duration to 1.0 seconds
// and in the animations block change the background color
// to red and the x-position of the frame
UIView.animateWithDuration(1.0, animations: {
self.coloredSquare.backgroundColor = UIColor.blueColor()
self.coloredSquare.frame = CGRect(x: 0, y: 500, width: 50, height: 50)
}, completion: { animationFinished in
self.movementUp()
})
}
func movementUp() {
UIView.animateWithDuration(1.0, animations: {
self.coloredSquare.backgroundColor = UIColor.redColor()
self.coloredSquare.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
}, completion: { animationFinished in
self.movementDown()
})
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用WHILE做一个方法,直到条件为假,Xcode构建但模拟器停在启动屏幕,如果我取消while条件,动画工作但没有什么能阻止它...任何人都可以帮助我吗?谢谢
首先,摆脱while循环.在动画完成块,首先检查如果调用其他动画之前,动画完成 - 如果你取消了动画,也不会是真实的,所以动画将停止.在您的按钮方法中,您需要访问coloredSquare的表示层以获取其当前位置,并取消所有动画以使动画立即停止.
class ViewController: UIViewController {
var coloredSquare: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
[self .movement()];
}
func movement() {
coloredSquare.backgroundColor = UIColor.blueColor()
coloredSquare.frame = CGRect(x:0, y:500, width:50, height:50)
self.view.addSubview(coloredSquare)
movementDown()
}
func movementDown() {
UIView.animateWithDuration(3.0, animations: {
self.coloredSquare.backgroundColor = UIColor.blueColor()
self.coloredSquare.frame = CGRect(x: 0, y: 500, width: 50, height: 50)
}, completion: { animationFinished in
if animationFinished {
self.movementUp()
}
})
}
func movementUp() {
UIView.animateWithDuration(3.0, animations: {
self.coloredSquare.backgroundColor = UIColor.redColor()
self.coloredSquare.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
}, completion: { animationFinished in
if animationFinished {
self.movementDown()
}
})
}
@IBAction func stopBlock(sender: AnyObject) {
var layer = coloredSquare.layer.presentationLayer() as CALayer
var frame = layer.frame
println(frame)
coloredSquare.layer.removeAllAnimations()
coloredSquare.frame = frame // You need this to keep the block where it was when you cancelled the animation, otherwise it will jump to the position defined by the end of the current animation
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
5312 次 |
| 最近记录: |