【问题标题】:Manage 800 images using asset catalogs with Xcode and in an UICollectionView在 Xcode 和 UICollectionView 中使用资产目录管理 800 张图像
【发布时间】:2015-01-27 20:25:44
【问题描述】:

我正在创建一个带有自定义图像的表情符号键盘,它有 845 个不同的图像(如果包含 @1x、@2x 和 @3x,则为 2535 个)。将它们作为资产导入 Xcode 后,现在编译我的程序非常慢,并且在 iOS 模拟器中显示键盘需要 3 秒。

我用来显示表情符号的 UICollectionView 也有问题:滚动时它崩溃了。我试图将我的 UICollectionViewCell 限制为 UIView,其背景是表情符号,这样我就不会创建 UIImageView 但性能仍然很差。

这是我的 cellForItemAtIndexPath() 函数:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
    let emoji = UIImage(named: emojiCollections[collectionUsed][positionInCollection]) // Creating the UIImage with the asset
    let emojiBackgroundColor = UIColor(patternImage: emoji!) // Set the background of the cell.
    positionInCollection++
    return cell
}

对于这些问题,我想知道管理这些图像数量的最佳方法是什么,以及如何在 UICollectionView 中正确显示它们(即具有良好的滚动性能)。

谢谢!

【问题讨论】:

  • 边走边加载,避免资产目录

标签: ios xcode swift uiimage uicollectionview


【解决方案1】:

我假设您正在加载所有图像并将它们存储在内存中,这是您问题的根源。您应该仅在需要时动态加载表情符号图像。当您使用UIImage(named:...) 方法加载图像时,UIKit 会为您进行缓存。

对于UICollectionView,使用 backgroundColor 属性来设置图像不是一个好习惯。使用setBackgroundImage(image: UIImage) 方法创建UICollectionViewCell 子类,该方法将图像设置在UIImageView 上。在您的子类中,您还可以执行以下操作以确保在重用单元格之前卸载旧图像。

override func prepareForReuse() {
    super.prepareForReuse()
    imageView.image = nil
}

【讨论】:

  • 关于缓存部分,我应该在哪里使用UIImage(named:...)加载图像?例如在viewDidLoad 中使用UIImage 的数组?我真的不明白如何使用 UICollectionView 动态加载图像。
猜你喜欢
  • 2014-08-18
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多