Tra*_*bbs 2 objective-c uitableview ios
我将图像添加到我的tableView单元格中,这使它变得迟钝.我仍然是目标c的新手,我不明白是什么导致这个或如何解决它.任何帮助是极大的赞赏!
group[PF_GROUP_LOGO]只是我的数据库中的一个字符串,对每个对象都是唯一的.代码有效,尝试滚动时非常滞后.
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
PFObject *group = groups[indexPath.row];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:group[PF_GROUP_LOGO]]]];
cell.imageView.image = image;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d users", (int) [group[PF_GROUP_MEMBERS] count]];
cell.detailTextLabel.textColor = [UIColor lightGrayColor];
return cell;
}
Run Code Online (Sandbox Code Playgroud)
有很多工具可以帮助你解决这个问题.
在基本级别,问题是您在主线程上运行一个长进程,这会阻止UI.从非本地URL加载图像非常耗时,您应该在后台线程上执行此操作,因此不会阻止UI.
同样,有很多方法可以做到这一点,我强烈建议您对异步资源加载进行一些研究,但这是您可以在自己的示例范围内做的一件事:
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
PFObject *group = groups[indexPath.row];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // go to a background thread to load the image and not interfere with the UI
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:group[PF_GROUP_LOGO]]]];
dispatch_async(dispatch_get_main_queue(), ^{ // synchronize back to the main thread to update the UI with your loaded image
cell.imageView.image = image;
});
});
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d users", (int) [group[PF_GROUP_MEMBERS] count]];
cell.detailTextLabel.textColor = [UIColor lightGrayColor];
return cell;
}
Run Code Online (Sandbox Code Playgroud)
我还建议使用AFNetworking,因为作者已经构建了一个非常好的类别UIImageView,允许您自动在后台加载来自Web URL的图像.同样,在这个过程中有许多思想流派,这只是一个想法.我建议阅读本文以获得有关该主题的完整教程.
我希望这是有帮助的!
| 归档时间: |
|
| 查看次数: |
601 次 |
| 最近记录: |