在iPhone13 pro真机和测试机上CollectionView Cell 换行情况

场景描述(踩空过程)

本来是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

相关推荐
壹方秘境3 天前
我用Go语言开发了一个跨平台的HTTPS抓包和调试工具
前端·后端·ios
初级代码游戏9 天前
easy Photo Clean公测版:快速清理iPhone照片 邀请公测
ios·iphone
库奇噜啦呼9 天前
【iOS】RunLoop学习
学习·ios
黑科技iOS上架9 天前
iOS应用周末提交什么情况算卡审
经验分享·ios
zzb15809 天前
ios基础-MVC-UIView
ios·mvc·cocoa
kingbal9 天前
Flutter:Flutter SDK版本管理工具FVM
android·flutter·ios·android-studio·window
他们都不看好你,偏偏你最不争气9 天前
【iOS】Runtime - Part 2 && 消息发送:缓存、查找与转发
macos·ios·objective-c·cocoa
2501_9159184110 天前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview
他们都不看好你,偏偏你最不争气10 天前
【iOS】Runtime - Part 1 && 对象与类的本质
macos·ios·objective-c·cocoa