如何在UIKit中使用UICollectionViewCompositionalLayout正确渲染远程图像

问题描述 投票:0回答:1

我想显示一个 NSCollectionLayoutItem(包含来自远程的图像,其宽高比未知)水平占据设备屏幕,并且仍然在垂直方向获得正确的宽高比。

所以我使用 NSCollectionLayoutDimension.estimated(50) 点作为 height 。但图片下载后,高度仍然是50,不足以显示图片。

如何让布局自动适应图片内容。

图片链接在这里:[图片源] (https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png)

图片内容为:

运行结果是这样的

UICollectionView配置代码:

import UIKit

class ViewController: UIViewController {
    enum Section {
        case main
    }
    
    @IBOutlet weak var collectionView: UICollectionView!
    var dataSource: UICollectionViewDiffableDataSource<Section, Int>! = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.configDataSource()
        self.configLayout()
    }

    
    func configDataSource() {
        let imageCellReg = UICollectionView.CellRegistration<ImageCell,Int>(cellNib: UINib(nibName: "ImageCell", bundle: nil)) { cell, indexPath, itemIdentifier in
            
        }
        self.dataSource = UICollectionViewDiffableDataSource<Section, Int>(collectionView: self.collectionView, cellProvider: { collectionView, indexPath, itemIdentifier in
            return self.collectionView.dequeueConfiguredReusableCell(using: imageCellReg, for: indexPath, item: itemIdentifier)
        })
        
        var snapshot = NSDiffableDataSourceSnapshot<Section, Int>()
        snapshot.appendSections([.main])
        snapshot.appendItems(Array(0..<2))
        dataSource.apply(snapshot, animatingDifferences: false)

    }
    
    func configLayout(){
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension:.estimated(50))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize:groupSize, subitems: [item])
        let spacing = CGFloat(10)
        group.interItemSpacing = .fixed(spacing)

        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing = spacing
        section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)

        let layout = UICollectionViewCompositionalLayout(section: section)
        self.collectionView.collectionViewLayout = layout
    }

}

以及手机号码:

import UIKit
import SDWebImage

class ImageCell: UICollectionViewCell {
    @IBOutlet weak var imageContentView: UIImageView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        imageContentView.sd_setImage(with: URL(string: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"))
    }

}
ios swift uicollectionview uikit uicollectionviewcompositionallayout
1个回答
0
投票

非常简单的例子...

像这样设计你的单元格:

enter image description here

我们为图像视图提供了高度约束——该约束将在图像下载后更新。

细胞类别就这么简单:

class ImageCell: UICollectionViewCell {

    @IBOutlet var imageContentView: UIImageView!
    @IBOutlet var imgHeight: NSLayoutConstraint!
    
}

使用

SDWebImage
,我们将实现一个完成块,在其中我们将计算下载图像的纵横比高度,我们将用它来设置
imgHeight.constant
。然后我们调用
collectionView.collectionViewLayout.invalidateLayout()
告诉控制器重新布局单元格:

cell.imageContentView.sd_setImage (
    with: URL(string: urlStr),
    placeholderImage: UIImage(named: "somePlaceholder"),
    options: SDWebImageOptions(rawValue: 0),
    completed: { [weak self] image, error, cacheType, imageURL in
        guard let self = self,
              let img = image
        else { return }
        
        // calculate proportional height
        let iw = cell.imageContentView.frame.width
        let ih = (img.size.height / img.size.width) * iw
        
        // update the height contraint in the cell
        cell.imgHeight.constant = ih
        
        // tell the collection view to re-layout the cells
        self.collectionView.collectionViewLayout.invalidateLayout()
    }
)

        

这是一个完整的示例项目:https://github.com/DonMag/SDWebCV

© www.soinside.com 2019 - 2024. All rights reserved.