简体   繁体   English

从网络的标题区域视图中加载UIImageView的图像

[英]Load image for UIImageView in header section view from network

I use UITableView and want to display UIImageView with loaded image from network in section header. 我使用UITableView并希望在节头中显示带有网络加载图像的UIImageView So my method 所以我的方法

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section returns next UIView : - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section返回下一个UIView

    UIView * header = [UIView new];
    header.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    header.backgroundColor = UIColor.clearColor;
    UserDataModel * userData = [CoreDataService sharedInstance].userData;
    UIImageView * userImageView = [UIImageView new];
    userImageView.frame = CGRectMake(20, 20, self.view.frame.size.width * 0.3, self.view.frame.size.width * 0.3);
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: userData.photoPath]];
        if (data == nil) {

            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            userImageView.image = [UIImage imageWithData: data];
        });
    });
    [header addSubview:userImageView];
    return header;

And it works only after scrolling table view, I can't figure out what I did wrong. 它仅在滚动表视图后才起作用,我无法弄清楚自己做错了什么。 Please explain me why it is wrong and how to do it correctly. 请向我解释为什么这是错误的,以及如何正确执行。 Thanks. 谢谢。

Reload the UIImageView after adding the image. 添加图像后重新加载UIImageView。

 dispatch_async(dispatch_get_main_queue(), ^{
        userImageView.image = [UIImage imageWithData: data];
        [userImageView setNeedsDisplay];
    });

First use SDWebImage to download it once as your current code will download it every header appearance 首先使用SDWebImage下载一次,因为您当前的代码会在每次标题显示时下载它

Second create an array of models (imagesUrls) for all header then loop for urls 第二个为所有标头创建模型数组(imagesUrls),然后循环访问url

UIImageView*img = [UIImageView new];

for (int section = 0; section < [myArray count]; section++)
{
    MyModel *model = [myArray objectAtIndex:section];

    [img sd_setImageWithURL:[NSURL URLWithString:model.url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {

          [tableView reloadSections:[[NSIndexSet alloc] initWithIndex:section] withRowAnimation:NO];
     }];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM