ios - Swift:collectionView 单元格
问题描述
我创建collectionView
并且我有 3 个单元格。我希望我的单元格在所有设备的所有屏幕上看起来都像这样:
但我有 iPad 的这个结果。
如何解决?
更新
我加collectionView
进去UIViewController
。我有这个限制collectionView
:
调整我的细胞大小:
代码:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow: CGFloat = 3
let itemWidth = (collectionView.bounds.width / itemsPerRow)
let itemHeight = itemWidth * 1.5
return CGSize(width: itemWidth, height: itemHeight)
}
解决方案
您需要自适应地更改单元格大小,否则该大小将不适用于所有屏幕尺寸。
您有您的功能,您可以在其中返回单元格大小:
return CGSize(width: 182, height: 275)
相反,让它像这样自适应:
return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)
或者,要在两者之间留出间隙,请创建一个偏移量:
let offset = 10
let width = self.view.frame.width - offset * 4 // 4 gaps
let height = self.view.frame.height - offset * 2 // 2 gaps
return CGSize(width: width / 3, height: height) // Divide into equally-sized cells
当然,self.view
可以用您希望单元格适合的任何容器替换。
推荐阅读
- algorithm - 与顺序无关的浮点求和
- javascript - 如何将 onclick 事件侦听器添加到 Javascript 中创建的按钮元素?
- file - 如何使用 Lua 导入文件夹
- jenkins - 詹金斯`如果(sh'...')`
- java - 使用 RequestParam 时 Spring Security 不断要求登录
- c++ - 将 QML 应用程序与 Qt5 (5.13.2) 静态链接
- azure-cognitive-services - 使用 Azure 转录威尔士语录音
- javascript - 如何根据用户输入发送 API 请求
- javascript - 此代码在 Angular JS 应用程序生命周期中的哪个位置加载
- visual-studio-code - VSCode - 禁用拖放时自动打开文件