场景描述(踩空过程)
本来是CollectionView两列展示的布局,在模拟器(xcode模拟器是iPhone15)上开发过程显示很正常、很符合预期。之后换iPhone13真机测试两列变一列,回过头用iPhone13的模拟器也是一样效果。打印计算出来的数值对比都是正确的,真让人头秃啊!
后来在StackOverflow上搜到有人遇到,他解决方法是计算出来的item宽度用floor
下取整。但到我这里没有直接取到效果,再把间距调小才重新显示两列。
ε=(´ο`*)))唉,汗颜~ 过程让人头秃~
其实总体思路是给横向水平上计算的值比设计长度短点,给间距minimumInteritemSpacing
多留空间,这样可以从间距调小和item调小两个方面入手。
解决方案
以下是遇到情况的代码(其他代码部分就是平常的CollectionView写法):
ini
// settingCollectionviewItem()方法在viewDidload中调用的
func settingCollectionviewItem() {
let columnCount = 2
let horizontalMargin: CGFloat = 14
let verticolMargin: CGFloat = 14
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = verticolMargin
flowLayout.minimumInteritemSpacing = horizontalMargin
flowLayout.sectionInset = UIEdgeInsets(top: verticolMargin, left: horizontalMargin, bottom: verticolMargin, right: horizontalMargin)
let colloctionWidth = myrCollectionView.frame.width
let itemWidth = (colloctionWidth - (CGFloat(columnCount - 1) * horizontalMargin + flowLayout.sectionInset.left + flowLayout.sectionInset.right)) / CGFloat(columnCount)
// Item宽高比152:220
let itemHeight = itemWidth * (220 / 152)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
myrCollectionView.collectionViewLayout = flowLayout
}
以下是采取的措施 (有更好的处理方法望评论区告知,还有知道为什么这个机型显示有问题也麻烦告知,不胜感激!):
ini
func settingCollectionviewItem() {
let columnCount = 2
let horizontalMargin: CGFloat = 14
let verticolMargin: CGFloat = 14
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = verticolMargin
flowLayout.minimumInteritemSpacing = horizontalMargin - 2
flowLayout.sectionInset = UIEdgeInsets(top: verticolMargin, left: horizontalMargin, bottom: verticolMargin, right: horizontalMargin)
let colloctionWidth = myCollectionView.frame.width
let itemWidth = floor((colloctionWidth - (CGFloat(columnCount - 1) * horizontalMargin + flowLayout.sectionInset.left + flowLayout.sectionInset.right)) / CGFloat(columnCount))
// Item宽高比152:220
let itemHeight = itemWidth * (220 / 152)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
myCollectionView.collectionViewLayout = flowLayout
}
参考文章
CollectionViewCells not displaying in middle on iPhone 13 Pro only