我想显示NSCollectionLayoutProject(包含来自远程的图像,其长宽比未知),水平占据设备屏幕,并且在垂直中仍然获得正确的长宽比.

因此,我使用NSCollectionLayoutDimensions. estimate(50)点来表示高度.但下载图像后,高度仍然是50,不足以显示图像.

如何使布局自动适合图像的内容.

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

image content is : enter image description here

运行结果就会是这样

enter image description here

UI CollectionView配置代码:

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"))
    }

}

推荐答案

非常快速的例子.

像这样设计您的单元格:

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

Ios相关问答推荐

在SwiftData中从@ Query创建可排序、有序和分组的数据

ITMS—91053:Flutter Project中缺少API声明

iPhone:iOS 17.4中没有气压数据

不使用iOS 17修改器修改SWIFT用户界面视图

删除领域中的cartItem时出现问题

为什么在Actor内部使用withTaskGroupwork并行运行?

无法在 CollectionView 中禁用部分弹跳 - 组合布局

在 SwiftUI 中使用 .rotation3DEffect 在视图之间翻转

弹出视图后使所有背景 UI 模糊

SwiftUI - ScrollView 不显示底部文本

在 SwiftUI 中将 TextEditor 文本计数连接到 ProgressView

如何避免任何绑定空错误并更好地获取代码

如何在 Swift 3 中根据 UIImage 的大小/比率调整 UIImageView 的大小?

检测 iPhone/iPad/iPod touch 的 colored颜色 ?

如何使用 swift 显示 .svg 图像

在 Swift 中禁用向后滑动手势

如何关闭 iOS 键盘?

如何使用完成按钮制作 UIPickerView?

什么是强属性属性

iOS 中的 Google Analytics SDK 3.0 _sqlite3 链接器错误