Ios UICollectionView边到边布局
目标:边缘到边缘UICollectionView,在所有尺寸的iPhone上安装2个电池Ios UICollectionView边到边布局,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,目标:边缘到边缘UICollectionView,在所有尺寸的iPhone上安装2个电池 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let screenSize = collectionVie
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)
}
也
但是在iPhone 6上:
集合单元格属性:
集合视图属性:
更新:
func表示渐变,它实际上获得了正确的宽度:
(位于自定义UICollectionViewCell类)
更新2:
注意:在iPhone7 Plus上进行测试。
我发现UICollectionViewFlowLayout覆盖了SizeFormiteIndeXPath:
中装箱的单元格大小(似乎是这样)
使用此代码:
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):
我明白了:
找到了解决方案。
问题出现在内部imageView自动布局设置中。我没有具体说明。
为什么那一小段废话妨碍了我的工作。我不知道。
对我来说更奇怪的是,为什么在第二次更新中手动指定cellEdgeLength为207时,它突然覆盖了imageView约束的缺失 您是否尝试过
返回CGSize(宽度:(self.collectionView!.frame.width/2),高度:(self.collectionView!.frame.width/2))
?框架=使用父视图坐标系边界的视图位置和大小=使用自己坐标系的视图位置和大小无效。有什么可以提供一些线索-我的单元格中有一个渐变视图,它的宽度合适。我会用渐变的代码更新我的og帖子。也许会有帮助。我可以看到你对渐变视图有限制,这些限制是用来做什么的?你试过没有吗?所以,对于单元格,没有约束,只有“后代”。对于集合视图,我认为这些数字不会影响任何东西。我删除了它们,没有任何变化。
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)
}
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
let cellSide: CGFloat = 207
flow.itemSize = CGSize(width: cellSide, height: cellSide)
flow.scrollDirection = UICollectionViewScrollDirection.vertical
flow.minimumInteritemSpacing = 0
flow.minimumLineSpacing = 0
collectionView.collectionViewLayout = flow