我试图旋转一个UIImageView 360度,并在网上看了几个教程。我不能让它们都工作,UIView要么停止,要么跳转到一个新位置。
我怎样才能做到这一点呢?
我最近尝试的是:
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
但如果我使用2*pi,它根本不会移动(因为它是相同的位置)。如果我尝试只做(180度),它可以工作,但如果我再次调用这个方法,它会向后旋转。
编辑:
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
[UIView setAnimationRepeatCount:HUGE_VALF];
[UIView setAnimationBeginsFromCurrentState:YES];
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
也不管用。它会转到180度,暂停一秒钟,然后在重新开始之前重置回0度。
如果有人想要nates的解决方案,那么这里是一个粗略的swift翻译:
class SomeClass: UIViewController {
var animating : Bool = false
@IBOutlet weak var activityIndicatorImage: UIImageView!
func startSpinning() {
if(!animating) {
animating = true;
spinWithOptions(UIViewAnimationOptions.CurveEaseIn);
}
}
func stopSpinning() {
animating = false
}
func spinWithOptions(options: UIViewAnimationOptions) {
UIView.animateWithDuration(0.5, delay: 0.0, options: options, animations: { () -> Void in
let val : CGFloat = CGFloat((M_PI / Double(2.0)));
self.activityIndicatorImage.transform = CGAffineTransformRotate(self.activityIndicatorImage.transform,val)
}) { (finished: Bool) -> Void in
if(finished) {
if(self.animating){
self.spinWithOptions(UIViewAnimationOptions.CurveLinear)
} else if (options != UIViewAnimationOptions.CurveEaseOut) {
self.spinWithOptions(UIViewAnimationOptions.CurveEaseOut)
}
}
}
}
override func viewDidLoad() {
startSpinning()
}
}
@ram的回答很有帮助。以下是Swift版本的答案。
斯威夫特2
private func rotateImageView() {
UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(M_PI_2))
}) { (finished) -> Void in
if finished {
self.rotateImageView()
}
}
}
斯威夫特3、4、5所示
private func rotateImageView() {
UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: { () -> Void in
self.imageView.transform = self.imageView.transform.rotated(by: .pi / 2)
}) { (finished) -> Void in
if finished {
self.rotateImageView()
}
}
}