iOS:从NSThread动画图片旋转

时间:2014-11-10 16:07:57

标签: ios objective-c rotation

我试图让图片在它的中心周围连续旋转。我创建了一个调用调用委托方法的线程来更新图片的旋转。我完全跑完,但旋转不会改变。 旋转设置为

 _myImageView.transform = CGAffineTransformMakeRotation(newRad);

当我把

_myImageView.transform = CGAffineTransformMakeRotation(M_PI_2);

进入viewDidLoad方法,图像变换90°。 如果执行了下面的代码,它就不会执行任何操作,尽管正确调用了hasUpdated方法。变量newRad包含有效值。 那么图像不会旋转的原因是什么呢? 谢谢你的帮助。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a
    [self setDelegate:self];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)hasUpdated:(int)x{
    // Convert Degree to Radian and move the needle

    float newRad =  x * M_PI / 180.0f;
    _myImageView.transform = CGAffineTransformMakeRotation(newRad);

}


- (IBAction)myTest:(id)sender {

    NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myLoop) object:nil];
    [myThread start];
}

- (void) myLoop
{
    int x = 1;
    while(true)
    {


        x++;
        if(x==360)
        {
            x = 1;
        }
        sleep(1);
        [self.delegate hasUpdated:x];
    }
}

1 个答案:

答案 0 :(得分:1)

由于您尝试从hasUpdated:方法更新用户界面,而myTest:方法已被NSThread方法调用,而IBAction方法又被NSThread中的选择器调用hasUpdated:,您实际上是在尝试从这个新_myImageView.transform = CGAffineTransformMakeRotation(newRad); 更新用户界面;但您只能从主线程更新应用的用户界面。

为了在其中的方法期间仍然更新UI的同时维护这个新线程,你可以通过坚持dispatch_async(dispatch_get_main_queue(), ^{ _myImageView.transform = CGAffineTransformMakeRotation(newRad); });

中的这一行来强制UI在主线程上更新
{{1}}

进入下面的块,如下:

{{1}}