ios - 如何在所有设备中快速布局每行三个图像
问题描述
所以基本上我有一个看起来像这样的集合视图布局:
这是一个每行 3 个图像,像 instagram 一样彼此非常接近。这里的问题是,当我使用 ipad 或像 iphone se 这样的小型手机时,布局会失真。这是它在 ipad 上的样子
集合视图布局代码是这样的:
func callCustomFlowLayout(collectionView: UICollectionView) {
let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemSpacing: CGFloat = 1
let itemsInOneLine: CGFloat = 3
flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1) //collectionView.frame.width is the same as UIScreen.main.bounds.size.width here.
flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
flow.minimumInteritemSpacing = 1
flow.minimumLineSpacing = 1
}
感谢您对未来的任何帮助。我只希望它是每行 3 个图像,并根据设备的大小调整图像大小。
这是我的布局代码
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellsAcross: CGFloat = 3
let spaceBetweenCells: CGFloat = 1
let dim = (collectionView.bounds.width - (cellsAcross - 1) * spaceBetweenCells) / cellsAcross
return CGSize(width: dim, height: dim)
}
解决方案
class CollectionView: UICollectionView {
private let numberOfCellsPerRow = 3
private let spacing: CGFloat = 1
private var flowLayout: UICollectionViewFlowLayout? {
return collectionViewLayout as? UICollectionViewFlowLayout
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
sharedInit()
updateItemSize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
updateItemSize()
}
private func sharedInit() {
flowLayout?.minimumInteritemSpacing = spacing
flowLayout?.minimumLineSpacing = spacing
}
private func updateItemSize() {
let cellWidth = floor((bounds.width - (CGFloat(numberOfCellsPerRow) - 1) * spacing) / CGFloat(numberOfCellsPerRow))
flowLayout?.itemSize = CGSize(width: cellWidth, height: cellWidth)
flowLayout?.invalidateLayout()
}
override var bounds: CGRect {
didSet {
if bounds != oldValue {
updateItemSize()
}
}
}
}
结果是:
推荐阅读
- webdriver-io - WebdriverIO 在尝试运行测试时出错
- java - Java:while循环未检测到中断条件,但如果块检测到
- python - 单击展开按钮后抓取数据
- powershell - Powershell中的问题不使用ReadKey
- node.js - Node.JS + Express 解析服务器上的 CSV 文件
- mysql - 如何使用子查询优化连接查询
- .net - ng2-pdfjs-viewer 打印功能打印整个 html 页面,而不是查看器中嵌入的 pdf 文档
- sql - Oracle SQL如何将具有不同数据的行合并为单行
- sql - 旋转数据库表
- apache-spark - 用于 Spark 结构化流的 Qubole Kinesis 连接器引发错误