使用UIActivityIndi​​cator进行UIButton操作

时间:2013-08-21 11:28:52

标签: ios multithreading uiimagepickercontroller uiactivityindicatorview

我正在尝试处理这样的事情:

我有一个UIButton动作正在调用UIImagePickerController并将其展示给拍摄。但是装载需要一段时间 - 特别是在第一次运行时。所以我决定在加载相机时放一个UIActivityIndicator来保持旋转。

但是我遇到了一个问题 - UIImagePicker正在主线程中加载,因此指标不会显示。我该如何解决这个问题?

这是我的方法:

- (IBAction)takePhoto:(UIButton *)sender
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

    UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.center=self.view.center;
    [self.view addSubview:activityView];
    [activityView startAnimating];

    [self presentViewController:imagePicker animated:NO completion:nil];
}

2 个答案:

答案 0 :(得分:2)

我遇到同样的问题,UIImagePickerController分配需要很长时间,所以为了避免主线程阻塞你可以使用下一个代码:

- (IBAction)takePhoto:(UIButton *)sender
{
    UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.center=self.view.center;
    [self.view addSubview:activityView];
    [activityView startAnimating];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:imagePicker animated:NO completion:nil];
        });
    });
}

答案 1 :(得分:1)

试试这个:

- (IBAction)takePhoto:(UIButton *)sender
{
     UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
     activityView.center=self.view.center;
     [self.view addSubview:activityView];
     [activityView startAnimating];

     int64_t delayInSeconds = 2.0;//How long do you want to delay?
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

         UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
         imagePicker.delegate = self;
         imagePicker.allowsEditing = YES;
         imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

         [self presentViewController:imagePicker animated:NO completion:nil];
     });         
}