【发布时间】:2019-02-27 22:04:48
【问题描述】:
我有一个UICollectionView,每行有 7 个项目(或者实际上,每个项目的宽度是 collectionView.bounds.width 除以 7)。
这是一个代码示例:
final class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let randomColors: [UIColor] = [.red, .blue, .green, .yellow, .orange, .purple, .cyan, .gray, .darkGray, .lightGray, .magenta]
var colors: [UIColor] {
var result: [UIColor] = []
for _ in 0..<200 {
result.append(randomColors[Int(arc4random_uniform(UInt32(randomColors.count - 1)))])
}
return result
}
@IBOutlet weak var collectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width / 7, height: 45)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return .leastNormalMagnitude
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return .leastNormalMagnitude
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: .leastNormalMagnitude, left: .leastNormalMagnitude, bottom: .leastNormalMagnitude, right: .leastNormalMagnitude)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionViewCell", for: indexPath) as! ColorCollectionViewCell
cell.color = colors[indexPath.row]
return cell
}
}
final class ColorCollectionViewCell: UICollectionViewCell {
var color: UIColor? {
didSet {
self.backgroundColor = color
}
}
}
还有故事板:
由于将collectionView 的宽度除以 7 通常会产生浮动结果,这会导致某些单元格之间出现空格:
我可以在这里做什么?
感谢您的帮助。
【问题讨论】:
-
你必须让一些单元格宽 1px。
标签: ios uicollectionview