首页 > 解决方案 > UICollectionView全宽高问题

问题描述

UICollectionView 宽度不是全宽,每行一个单元格

UICollectionView

private func setCollectionView() {

    let layout = UICollectionViewFlowLayout()
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.scrollDirection = .horizontal

    collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.isPagingEnabled = true
    collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "cell")

}

UICollectionView -> 约束

    NSLayoutConstraint.activate([
        view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
        view.topAnchor.constraint(equalTo: collectionView.topAnchor),
        view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
    ])

UIColletionViewCellSize

通过添加UICollectionViewFlowLayoutDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}

ImageCollectionViewCell

class ImageCollectionViewCell: UICollectionViewCell {
....
    private let imageView: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFill
        img.translatesAutoresizingMaskIntoConstraints = false
        return img
    }()
....
}

ImageCollectionViewCell -> imageView 约束

   addSubview(imageView)

    NSLayoutConstraint.activate([
        leadingAnchor.constraint(equalTo: imageView.leadingAnchor),
        trailingAnchor.constraint(equalTo: imageView.trailingAnchor),
        topAnchor.constraint(equalTo: imageView.topAnchor),
        bottomAnchor.constraint(equalTo: imageView.bottomAnchor)
    ])

UICollectionView FlowLayout 警告

项目高度必须小于 UICollectionView 的高度减去部分插入顶部和底部值,减去内容插入顶部和底部值。

相关的 UICollectionViewFlowLayout 实例是 ,它附加到 ; 层 = ; 内容偏移:{0,-44};内容大小:{0, 0}; adjustedContentInset: {44, 0, 34, 0}> 集合视图布局: .

这是不断发生

https://gph.is/g/EqNL8jr

标签: iosswiftuicollectionview

解决方案


UICollectionView 警告修复

    if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } 
    else { automaticallyAdjustsScrollViewInsets = false } 

Scale to fill 提供比 UIImageView 尺寸更大的图像

    img.clipsToBounds = true

推荐阅读