加载本地GIF在Swift中获取内存警告



我有一个可扩展的collapsalbe tableview,该tableView在扩展时显示了多个gif文件。在某个时间,当我一次又一次扩展多个部分时,它在到达600 MB空间时会随着内存警告而崩溃。

我的实现:

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let imageView = UIImageView()
    imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) 
    DispatchQueue.global(qos: .background).async {
        DispatchQueue.main.async {
           let imageData = try! Data(contentsOf: Bundle.main.url(forResource: "compile_animatiion", withExtension: "gif")!)
            //imggview.image = UIImage.gif(data: imageData)
            imageView.image =  UIImage.gifImageWithData(imageData) 
            cell.addSubview(imageView)
        }
    }
    cell.addSubview(imageView)
   }

我的代码正在使用类UIIMAGE GIF,您可以轻松地从git获得它。我需要确切的技术来避免此内存警告。

示例来源:drive.google.com/open?id=1tlvwaofwoaronf91yykutdy_c0ilhazq

改进
1.避免在方法cellForRowAt中创建无限图像视图。
2.与所有重复使用的单元格共享全局GIF图像数据。

代码

private var _gifImageData:UIImage?
var gifImageData:UIImage! {
    get{
        if (_gifImageData != nil) {
            return _gifImageData
        }
        else{
            let imageData = try! Data(contentsOf: Bundle.main.url(forResource: "compile_animatiion", withExtension: "gif")!)
            _gifImageData = UIImage.gifImageWithData(imageData)
            return _gifImageData
        }
    }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
    let tagOfGifImageView = 1283
    if cell.viewWithTag(tagOfGifImageView) == nil {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        imageView.tag = tagOfGifImageView
        imageView.image = self.gifImageData
        cell.addSubview(imageView)
    }
    return cell
}

最新更新