show spinner and remove it in the same block

2019-02-05 07:59发布

In a method that can take up to several seconds i have:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
spinner.color = [UIColor blueColor];
[spinner startAnimating];
[_mapViewController.view addSubview:spinner];

// lots of code

[spinner removeFromSuperview];

The spinner doesn't show up. Probably since the screen doesn't get update at that time. How can i get around this problem?

1条回答
Lonely孤独者°
2楼-- · 2019-02-05 08:26

Use GCD:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
spinner.color = [UIColor blueColor];
[spinner startAnimating];
[_mapViewController.view addSubview:spinner];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // lots of code run in the background

    dispatch_async(dispatch_get_main_queue(), ^{
        // stop and remove the spinner on the main thread when done
        [spinner removeFromSuperview];
    });
});
查看更多
登录 后发表回答