UICollectionView边到边布局

时间:2017-02-03 00:33:22

标签: ios swift uicollectionview uicollectionviewcell

目标:边缘到边缘的UICollectionView,在所有尺寸的iPhone上都有2个单元格。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

   let screenSize = collectionView.bounds
    let screenWidth = screenSize.width
    print("Zhenya: \(screenWidth)") // prints correct 375, which is half of iPhone 6
    let cellEdgeLength: CGFloat = screenWidth / 2.0

    return CGSize(width: cellEdgeLength, height: cellEdgeLength)
}

另外

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.delegate = self
    collectionView.dataSource = self

    let flow = UICollectionViewFlowLayout()
    flow.scrollDirection = UICollectionViewScrollDirection.vertical
    flow.minimumInteritemSpacing = 0
    flow.minimumLineSpacing = 0
    collectionView.collectionViewLayout = flow
}

但是在iPhone 6上:

enter image description here

收集单元格属性:

enter image description here

集合视图属性:

enter image description here

更新 渐变的func,实际得到正确的宽度: (位于自定义UICollectionViewCell类)

  func addGradient () {

    let gradient = CAGradientLayer()
    gradient.frame = gradientView.bounds
    let topColor = UIColor(red:0.07, green:0.07, blue:0.07, alpha:1)
    let botomColor = UIColor.clear
    gradient.colors = [topColor.cgColor, botomColor.cgColor]

    if gradientWasRemoved == false {
    gradientView.layer.insertSublayer(gradient, at: 0)
    } else if gradientWasRemoved == true {
        self.addSubview(gradientView)
    }

更新2: 注意:在iPhone 7 Plus上进行测试。 我发现UICollectionViewFlowLayout会覆盖sizeForItemAtIndexPath:中包含的单元格大小(看起来像这样) 使用此代码:

    let flow = UICollectionViewFlowLayout()
    let screenSize = collectionView.bounds
    let screenWidth = screenSize.width
    let cellEdgeLength: CGFloat = screenWidth / 2.0

    flow.itemSize =  CGSize(width: cellEdgeLength, height: cellEdgeLength)

    flow.scrollDirection = UICollectionViewScrollDirection.vertical
    flow.minimumInteritemSpacing = 0
    flow.minimumLineSpacing = 0
    collectionView.collectionViewLayout = flow

我有这个:

enter image description here

然后我决定手动指定单元格边长(iPhone7Plust宽度的一半= 207):

 let cellSide: CGFloat = 207
 flow.itemSize =  CGSize(width: cellSide, height: cellSide)

 flow.scrollDirection = UICollectionViewScrollDirection.vertical
 flow.minimumInteritemSpacing = 0
 flow.minimumLineSpacing = 0
 collectionView.collectionViewLayout = flow

我明白了:

enter image description here

1 个答案:

答案 0 :(得分:0)

找到解决方案。 问题出在内部imageView自动布局设置中。我没有指定它们。 为什么那个小小的BS正在走向我的flow.itemSize,我不知道。 更让我感到奇怪的是,为什么在第二次更新时手动指定cellEdgeLength为207,突然之间,它确实覆盖了缺少imageView约束。