【问题标题】:Load local gif in swift get memory warning快速加载本地 gif 获取内存警告
【发布时间】:2018-07-28 16:16:23
【问题描述】:

我有一个可展开和折叠的表格视图,它在展开时会显示多个 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

【问题讨论】:

    标签: ios swift gif


    【解决方案1】:

    改进
    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
    }
    

    【讨论】:

    • 我有 44 个单独的 gif。同样的问题仍然存在:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2018-03-09
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多