2012-07-17 65 views
0

我们在iOS上的tableView上方显示视图时出现问题。我们的方法 是创建一个UIView,它是UIViewController的一个子类的子视图,发送 它到后面,然后将它带到didSelectRowAtIndexPath的前面。 我们使用XIB创建用户界面。视图层次是像 这样的:UIView UITableView上方没有显示 - iOS

查看
- UIView的( “载入中...” 视图)
- - 的UILabel( “载入中...”)
- - UIActivityIndi​​catorView
- UITableView的
- 的UILabel

这是我们正在做的尝试,以显示 “加载” 观点:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Create a request to the server based on the user's selection in the table view 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
    NSError *err; 

    // Show the "loading..." message in front of all the other views. 
    [self.view bringViewToFront:self.loadingView]; 
    [self.loadingWheel startAnimating]; 

    // Make the request 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err]; 

    // Stop animating the activity indicator. 
    [loadingWheel stopAnimating]; 

    // other stuff... 
} 

每当我们在 XIB中的所有其他视图的前面离开“加载”视图时,我们可以看到它看起来像我们想要的。但是,当我们在后面(根据上面的视图层次)加载 视图,然后尝试将它放到前面 时,视图将永不显示。打印出self.view.subviews表明我们的 加载视图实际上在视图层次结构中。有趣的是,如果我们尝试在didSelectRowAtIndexPath内更改我们视图中的其他内容(例如, 更改已在视图中显示的标签的背景色), 更改从不在模拟器上显示。

回答

2

问题是同步请求。它会阻止主线程,所以活动指示器无法显示。

一个简单的解决方案是将数据异步加载到全局队列中,并且在加载所有内容时调用主队列。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // Make the request 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // Stop animating the activity indicator. 
     [loadingWheel stopAnimating]; 

     // other stuff... 
    }); 
}); 

虽然上面的解决方案工作,它会阻止全局队列,所以它不是理想的。看看通过NSURLConnection的异步加载。这在Apple的“URL加载系统编程指南”中有详细的解释。

+0

现在我们全部拿出了同步请求。虽然我们代码的最终评论中提到的“其他内容”涉及发布导致一些异步请求的通知,但我们的“加载”视图仍然不会显示。 – Peter 2012-07-18 18:29:33

+0

这对我来说很好。我只保留了两行,将subview放在前面并开始动画,并将'bringViewToFront:'改成'bringSubviewToFront:'(这是正确的方法名称)。检查一切是否与XIB文件连接,即确保self.view,self.loadingView等连接到正确的对象。 – 2012-07-19 08:36:06