我正在尝试通过按钮停止在视图中循环播放的正方形动画(上下循环)并读取位置(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()
    })
}

如果我尝试在条件不成立之前尝试执行某种方法,则将构建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
}

}

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

10-12 00:40
查看更多