didSelectRowAtIndexPath中的AddSubview

时间:2013-06-26 07:47:54

标签: ios uitableview uiactivityindicatorview addsubview

我有一个问题。

我有表格视图,当我点击单元格时,我从服务器加载数据。因为这可能需要一些时间才能显示活动指示器视图。

-(void)startSpiner{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UIView * background = [[UIView alloc]initWithFrame:screenRect];
    background.backgroundColor = [UIColor blackColor];
    background.alpha = 0.7;
    background.tag = 1000;

    UIActivityIndicatorView * spiner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spiner.frame = CGRectMake(0, 0, 50, 50);
    [spiner setCenter:background.center];
    [spiner startAnimating];
    [background addSubview:spiner];
    [background setNeedsDisplay];
    [self.view addSubview:background];
}

这很好用,但是当我把它放在

中时
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self startSpiner];
    Server *server = [[Server alloc]init];
    self.allItems = [server getDataGLN:self.object.gln type:1];
}

我看到UIActivityIndi​​catorView在从服务器获取数据后显示。 如何强制主视图立即更新?

3 个答案:

答案 0 :(得分:2)

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self startSpiner];

     ////If your server object is performing some network handling task. dispatch a
     ////background task.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        Server *server = [[Server alloc]init];

        self.allItems = [server getDataGLN:self.object.gln type:1];
    });
}

答案 1 :(得分:0)

为什么要调用setNeedsDisplay?

无论如何,正确的方法是,当您想要显示加载指示符时,不会创建所有UI。 提前做 - 例如在ViewDidLoad中,只隐藏背景视图。 如果要显示它,只需将其隐藏属性设置为NO。

答案 2 :(得分:0)

在代码将控制权返回到运行循环之前,UI通常不会更新。在从服务器获取数据之前,您的getDataGLN:type:方法不会返回。因此,在您从服务器获取数据之前,无法更新UI。

不要那样做。在后台线程上加载数据并立即将主线程的控制权返回到运行循环。您会在Concurrency Programming GuideApple's developer videos中找到很多帮助。