【问题标题】:UICollectionView full width and height problemUICollectionView全宽高问题
【发布时间】:2020-01-03 15:39:02
【问题描述】:

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 的高度减去 section insets 顶部和底部值,减去 content insets 顶部和底部值。

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

这一直在发生

https://gph.is/g/EqNL8jr

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    UICollectionView 警告修复

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

    Scale to fill 给出的图片比 UIImageView 的尺寸大

        img.clipsToBounds = true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      相关资源
      最近更新 更多