UIActivityIndi​​catorView没有凝视

时间:2015-06-06 00:31:11

标签: ios objective-c uitableview uiactivityindicatorview nsthread

我试图在我的'UITableViewCell'之一中设置'UIActivityIndi​​catorView'作为accessoryView,这样,当用户触摸此单元格时,ActivityIndi​​cator开始动画。我在'didSelectRowAtIndexPath'方法中添加以下代码:

UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

UIActivityIndicatorView * activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

NSThread * newThread1 = [[NSThread alloc]initWithTarget:self selector:@selector(carregarNoticias) object:nil];

switch (indexPath.row) {
    case 0:
        cell.accessoryView = activity;
        [activity startAnimating];
        sleep(0.01);
        [newThread1 start];

        while (![newThread1 isFinished]) {
            //waiting for thread
       }

        [activity stopAnimating];
[self.navigationController pushViewController:noticias animated:YES];
break; 

当newthread1正在运行时,我期待'UIActivityIndi​​catorView'动画。但是,动画仅在newThread1完成时开始(因此我不再需要动画)。我加了0.01秒作为睡眠时间给动画开始时间。然而,这也没有解决。

有谁知道我的错误是什么?我感谢任何帮助!

1 个答案:

答案 0 :(得分:-1)

我真的不知道你想要做什么如此添加延迟..尝试下面的这一行,可能是你寻找的那个......还有另一件事......请不要像sleep(0.01);那样阻止主线程用户不喜欢它..

cell.accessoryView = activity;

[activity startAnimating];

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

    // the system will wait until this 
    dispatch_async(dispatch_get_main_queue(), ^(void){

        [newThread1 start];

    });
    // is finished, maybe you dont need the `[NSThread sleepForTimeInterval:3];` 
    // pick the one that suits your implementation.. 

    [NSThread sleepForTimeInterval:3];

    dispatch_async(dispatch_get_main_queue(), ^(void){

        [activity stopAnimating];

        [self.navigationController pushViewController:noticias animated:YES];

    });
});

[NSThread sleepForTimeInterval:3]像你拥有sleep(0.01);

那样睡觉线程

但在

中使用它
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){  });

使其异步。并且不会阻止主线程..

dispatch_async(dispatch_get_main_queue(), ^(void){在主线程中激活你的代码..

快乐的编码,干杯! :)