Objective-C 中 AQGridView 延迟加载图像

发布于 2025-01-07 07:59:40 字数 970 浏览 2 评论 0原文

在我的应用程序中,我有一个根视图,它是一个网格视图。我正在 gridview 单元格中加载图像。我在加载图像时遇到问题。一旦我启动应用程序,图像加载到单元格中一秒钟后,就会出现没有图像的空白单元格。有什么办法可以解决这个问题吗?下面是我的代码。

UIImage *defaultImage = [UIImage imageNamed:@"addEmployee.png"];
if (!employee.imageName) {
    return defaultImage;
}

  if ([_imageCache objectForKey:employee.imageName]) {
      return [_imageCache objectForKey:employee.imageName];
  }

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    UIImage *image = [UIImage imageWithContentsOfFile:[self  imagePath:employee.imageName]];
    dispatch_async(dispatch_get_main_queue(), ^ {
        if (image) {
            [_imageCache setObject:image forKey:employee.imageName];
            cell.imageView.image = image;
        } else {
            [_imageCache setObject:defaultImage forKey:employee.imageName];
            cell.imageView.image = defaultImage;
            return;
        }
    });
});

 return cell.imageView.image;

}

In my app, I have a root view which is a gridview. I am loading an images in the gridview cells.I am having problem with the loading images. As soon as I launch the app, there will be blank cells with out images after a second the images are loading into the cells. Is there any way to solve this issue. The below is my code.

UIImage *defaultImage = [UIImage imageNamed:@"addEmployee.png"];
if (!employee.imageName) {
    return defaultImage;
}

  if ([_imageCache objectForKey:employee.imageName]) {
      return [_imageCache objectForKey:employee.imageName];
  }

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    UIImage *image = [UIImage imageWithContentsOfFile:[self  imagePath:employee.imageName]];
    dispatch_async(dispatch_get_main_queue(), ^ {
        if (image) {
            [_imageCache setObject:image forKey:employee.imageName];
            cell.imageView.image = image;
        } else {
            [_imageCache setObject:defaultImage forKey:employee.imageName];
            cell.imageView.image = defaultImage;
            return;
        }
    });
});

 return cell.imageView.image;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谢绝鈎搭 2025-01-14 07:59:40

加载图像需要时间,没有办法让它即时完成。您的代码似乎很合理,您正在从主线程加载图像,因此它不会阻塞 UI,并在加载后缓存它们。使其更快的唯一方法是加载更少的图像或使图像更小。

Loading images takes time, there is no way to make it instant. Your code seems sensible, you are loading the images off the main thread so it will not block the UI, and caching them once loaded. The only way to make it faster is to load less images or make the images smaller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文