我正在關注本教程:

基本上是水平collectionView輸入section 1和垂直collectionView輸入section 2
我的想法是在第一個單元格中放置一個 collectionView ,它應該具有以下大小: CGSize(width: screen.width, height: 100)
但是由于我使用的是鏈接中的方法,因此我不知道如何為第一個單元格指定特定大小。這是我嘗試過的:

uj5u.com熱心網友回復:
免責宣告:作為OP曾問一個問題,前面關于如何創建一個Pinterest的布局,我曾建議在評論Raywenderlich教程中,我相信從OP這個問題是該分機
回答:
查看您添加的設計,我相信您正在嘗試添加一個CollectionView帶有水平滾動條的單元格,作為跨越整個集合視圖寬度的第一個單元格。因為你已經子類化了UICollectionViewFlowLayout你需要在prepare方法本身中處理這個特殊情況
override func prepare() {
// 1
guard
cache.isEmpty,
let collectionView = collectionView
else {
return
}
// 2
let columnWidth = contentWidth / CGFloat(numberOfColumns)
var xOffset: [CGFloat] = []
for column in 0..<numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth)
}
var column = 0
var yOffset: [CGFloat] = .init(repeating: 0, count: numberOfColumns)
// 3
for item in 0..<collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let attributes: UICollectionViewLayoutAttributes
let photoHeight = delegate?.collectionView(
collectionView,
heightForPhotoAtIndexPath: indexPath) ?? 180
let height = cellPadding * 2 photoHeight
let frame: CGRect
if item == 0 {
frame = CGRect(x: 0,
y: yOffset[column],
width: columnWidth,
height: height)
contentHeight = frame.maxY
for column in 0..<numberOfColumns {
yOffset[column] = frame.maxY
}
column = 0
}
else {
// 4
frame = CGRect(x: xOffset[column],
y: yOffset[column],
width: columnWidth,
height: height)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] height
column = column < (numberOfColumns - 1) ? (column 1) : 0
}
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
}
}
在您的for item in 0..<collectionView.numberOfItems(inSection: 0) {我添加了一個特殊條件來處理if item == 0 {where in 而不是使用列寬,我使用了內容寬度(根據您的設計,您希望第一個單元格覆寫集合視圖的整個寬度)
最后在您的委托方法中
extension PhotoStreamViewController: PinterestLayoutDelegate {
func collectionView(
_ collectionView: UICollectionView,
heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 180 // whatever is the height of first cell
}
return photos[indexPath.item].image.size.height
}
}
一句小心的話
在您的設計中,我可以看到您添加了兩個部分標題Header 1 和Header 2我猜在這種情況下您回傳的部分數量至少為 2,但本教程側重于單個部分集合視圖,如果您注意到
for item in 0..<collectionView.numberOfItems(inSection: 0) {
第 0 部分是硬編碼的,如果您想處理多個部分,則可能需要動態處理它,并且可能需要大量返工 prepare
uj5u.com熱心網友回復:
為了獲得控制集合項大小的能力,您可能遵循的一種策略是讓UICollection視圖的委托派生自 ,UICollectionViewDelegateFlowLayout而不僅僅是來自UICollectionViewDelegate。通過從UICollectionViewDelegateFlowLayout您的委托派生可以實作:
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize
并告訴系統第一項的大小。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340168.html
