正如您已经发现的那样,将 320 点宽的屏幕分成 7 等份是不可能的。
但是,如果一个单元格比另一个单元格大或小半个甚至一个点,没人会注意到。您可以使用一点数学来获得整数像素值(即 0.5 点)。
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size: CGSize!
let column = indexPath.item % 7
let width = collectionView.bounds.size.width
let height = 80.0
if width == 320.0 {
// iPhone 5
// 46 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 46
if column == 0 || column == 6 {
size = CGSize(width: 46, height: height)
}
else {
size = CGSize(width: 45, height: height)
}
}
else if width == 375.0 {
// iPhone 6
// 53 + 0,5 + 53 + 0,5 + 53 + 0,5 + 54 + 0,5 + 53 + 0,5 + 53 + 0,5 + 53
if column == 3 {
size = CGSize(width: 54, height: height)
}
else {
size = CGSize(width: 53, height: height)
}
}
else if width == 414.0 {
// iPhone 6 Plus
// 58 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 58
if column == 0 || column == 6 {
size = CGSize(width: 58, height: height)
}
else {
size = CGSize(width: 59, height: height)
}
}
else {
println("Unhandled Width: \(width)")
abort()
}
return size
}
这只是一个示例,我已经准备好了,因为我目前正在处理日历视图。每个单元格之间有 1 个像素的间距。
对于没有间距的 320 pt 宽的单元格布局,您可以使用类似 45.5+45.5+46+46+46+45.5+45.5