【发布时间】:2017-12-07 06:34:55
【问题描述】:
我有一个非常简单的 UICollectionView 要求。对于 iPhone 6/6s/7 和 6/6s/7 Plus 尺寸,两个单元格必须并排显示,即每行两个单元格。对于 iPhone 5/5s/SE,它应该每行显示 1 个单元。我的单元格高度几乎固定为 194。
现在我在视图控制器中有这段代码来实现这一点-
import UIKit
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var screenWidth: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
screenWidth = collectionView.frame.width
// Do any additional setup after loading the view, typically from a nib
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
// layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2)
layout.itemSize = CGSize(width: screenWidth / 2, height: 194)
layout.minimumInteritemSpacing = 0
collectionView.collectionViewLayout = layout
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.blue
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath as IndexPath) as UICollectionViewCell
cell.backgroundColor = UIColor.white
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 0.5
return cell
}
}
结果输出是这个-
如您所见,iPhone Plus 尺寸和 5/5s/SE 布局很好,或者我应该说我对那些拥有我拥有的东西很好,但第二个即 6/6s/7 尺寸的单元格几乎粘在一起。我知道我有 layout.minimumInteritemSpacing = 0,但如果我将其增加到 1,那么单元格将像第三张图片一样被向下推,使用 UIEdgeInsets 也会导致同样的问题。
我的整个 UICollectionView 都固定在 top 0 、 bottom 0 、 left 8 和 right 8 到超级视图上。我在 SO 中查看了一些与此相关的问答,并建议使用 UICollectionViewDelegateFlowLayout 的 sizeForItemAt 函数,但我也无法使用它来解决这个问题。
如何解决 6/6s/7 屏幕宽度的间距问题,以使两个单元格以一定间距排成一行?我的最终目标是在 6 及以上设备上每行有 2 个电池,在 5s 及以下设备(包括 SE)上每行 1 个电池。这个可以吗?
【问题讨论】:
标签: ios swift xcode uicollectionview uicollectionviewlayout