目标:在所有尺寸的 iPhone 上具有 2 个单元格的边到边 UICollectionView。
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 上:
集合单元格属性:
Collection View 属性:
更新: 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
我有这个:
然后我决定手动指定单元格边缘长度(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
我明白了:
最佳答案
找到了解决方案。 问题出在内部 imageView 自动布局设置中。我没有具体说明它们。 我不知道为什么那一小段废话会妨碍我的 flow.itemSize。 对我来说更奇怪的是,为什么当在第二次更新中手动将 cellEdgeLength 指定为 207 时,突然之间,它确实覆盖了 imageView 约束的缺乏。
关于ios - UICollectionView 边到边布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014849/