gpt4 book ai didi

ios - 使用按钮停止动画方 block

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:20 24 4
gpt4 key购买 nike

我试图用一个按钮停止在 View 中动画的正方形(循环上下)并读取位置(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()
})
}

如果我尝试使用 WHILE 执行方法直到条件为假,Xcode 构建但模拟器在启动屏幕停止,如果我取消 while 条件,动画工作但没有阻止它......谁能帮我?谢谢

最佳答案

首先,摆脱 while 循环。在动画的完成 block 中,首先检查动画是否已完成,然后再调用另一个动画——如果取消动画,则不会为真,因此动画将停止。在您的按钮方法中,您需要访问 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
}

关于ios - 使用按钮停止动画方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com