我想显示NSCollectionLayoutProject(包含来自远程的图像,其长宽比未知),水平占据设备屏幕,并且在垂直中仍然获得正确的长宽比.
因此,我使用NSCollectionLayoutDimensions. estimate(50)点来表示高度.但下载图像后,高度仍然是50,不足以显示图像.
如何使布局自动适合图像的内容.
图片链接在这里:[图片SRC](https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png)
运行结果就会是这样
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"))
}
}