在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

相关推荐
游戏开发爱好者820 分钟前
FTP 抓包分析实战,命令、被动主动模式要点、FTPS 与 SFTP 区别及真机取证流程
运维·服务器·网络·ios·小程序·uni-app·iphone
Nick56833 小时前
Xcode16 避坑
ios
ii_best3 小时前
IOS/ 安卓开发工具按键精灵Sys.GetAppList 函数使用指南:轻松获取设备已安装 APP 列表
android·开发语言·ios·编辑器
2501_915909063 小时前
iOS 26 文件管理实战,多工具组合下的 App 数据访问与系统日志调试方案
android·ios·小程序·https·uni-app·iphone·webview
hweiyu003 小时前
苹果iOS开发零基础特训(视频教程)
ios
2501_9159184117 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090620 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
非专业程序员Ping1 天前
新手小白也能看懂的LLDB技巧/逆向技巧
ios·assembly