我有一个网格视图,其中包含从互联网下载的图像。当我点击一个按钮进入该视图时,这需要时间,并且第一个屏幕被冻结,只有当所有图像都下载后,第二个视图才会显示。如何在我必须等待的时间上设置活动指示器?
将活动视图添加到您的单元格/视图中,如下所示:
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake(0, 0, 24, 24);
[self.view addSubview:spinner];
[spinner startAnimating];
当NSURLConnection委托方法通知您它们已完成时,调用[spinner stopAnimating];
并将其从其superView中删除。
还要确保只在主线程上调用上面的代码(与UI交互)。
首先,您不需要放置活动指示器并等待静态下载所有图像。。想象一下,如果有1000张图片,用户必须等到下载完成才能开始使用你的应用程序。
我假设这个gridView是tableView,因为在移动设计世界中gridView不会退出。
查看已加载
- (void)viewDidLoad {
[super viewDidLoad];
array = [[NSMutableArray alloc]initWithObjects:@"http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg", @"http://1hdwallpapers.com/wallpapers/creativity_water_spray_drops_flower_rose_desktop_images.jpg" , @"http://i.telegraph.co.uk/multimedia/archive/02848/wellcome-photo-13__2848386k.jpg" ,@"http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg" , @"http://www.hdwallpapersimages.com/wp-content/uploads/images/Frozen-Logo-Symbol-HD-Images.jpg" , @"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg" , @"http://www.desktopwallpaperhd.net/wallpapers/21/7/wallpaper-sunset-images-back-217159.jpg" , nil];
tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20) style:UITableViewStylePlain];
// DO NOT FORGET UITableViewDelegate, UITableViewDataSource protocols
[tableView setDelegate:self];
[tableView setDataSource:self];
[self.view addSubview:tableView];
}
行数:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [array count];
}
小区配置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//You need a global declaration for cell
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
[self getImagesAsyncFor:indexPath];
return cell;
}
现在获取ImagesAsync方法
-(void)getImagesAsyncFor:(NSIndexPath *)indexPath_ {
// Fetch using GCD
dispatch_queue_t downloadThumbnailQueue = dispatch_queue_create("Get Photo Thumbnail", NULL);
dispatch_async(downloadThumbnailQueue, ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[array objectAtIndex:indexPath_.row]]]];
dispatch_async(dispatch_get_main_queue(), ^{
cell = [self->tableView cellForRowAtIndexPath:indexPath_]; // create a copy of the cell to avoid keeping a strong pointer to "cell" since that one may have been reused by the time the block is ready to update it.
if (cell != nil) {
[cell.imageView setImage:image];
[cell setNeedsLayout];
}
});
});
}
现在,当您打开应用程序时,您应该看到图像是如何一个接一个异步下载的,并且您仍然可以与应用程序交互。下载完成后,tableView的UI将使用以下方法自动更新:[cell setNeedsLayout];
这就是所有现代应用程序的构建方式,比如facebook、twitter、google+等。