добавление пользовательского заголовка в Ray wenderlich Pinterest Layout - PullRequest
0 голосов
/ 02 июля 2018

Я использовал файл макета Pinterest, предоставленный Рэем Вендерлихом, и прекрасно реализовал желаемый макет для ячеек, однако в CollectionViewController, где я добавляю собственный заголовок, я хочу добавить слой Pinterest под собственным заголовком.
Но слой Pinterest переопределяет пользовательский заголовок, и я больше не могу найти пользовательский заголовок.

Любые предложения о том, как я могу решить эту проблему, были бы очень благодарны.

Файл макета Pinterest находится ниже:

import UIKit

protocol CustomLayoutDelegate: class {
    // 1. Method to ask the delegate for the height of the image
    func collectionView(_ collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat
}

class CustomLayout: UICollectionViewFlowLayout {

//1. Pinterest Layout Delegate
weak var delegate: CustomLayoutDelegate!

//2. Configurable properties
fileprivate var numberOfColumns = 2
fileprivate var cellPadding: CGFloat = 5

//3. Array to keep a cache of attributes.
fileprivate var cache = [UICollectionViewLayoutAttributes]()

//4. Content height and size
fileprivate var contentHeight: CGFloat = 0

fileprivate var contentWidth: CGFloat {
    guard let collectionView = collectionView else {
        return 0
    }
    let insets = collectionView.contentInset
    return collectionView.bounds.width - (insets.left + insets.right)
}

override var collectionViewContentSize: CGSize {
    return CGSize(width: contentWidth, height: contentHeight)
}

override func prepare() {
    // 1. Only calculate once
    guard cache.isEmpty == true, let collectionView = collectionView else {
        return
    }
    // 2. Pre-Calculates the X Offset for every column and adds an array to increment the currently max Y Offset for each column
    let columnWidth = contentWidth / CGFloat(numberOfColumns)
    var xOffset = [CGFloat]()
    for column in 0 ..< numberOfColumns {
        xOffset.append(CGFloat(column) * columnWidth)
    }
    var column = 0
    var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)

    // 3. Iterates through the list of items in the first section
    for item in 0 ..< collectionView.numberOfItems(inSection: 0) {

        let indexPath = IndexPath(item: item, section: 0)

        // 4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame.
        let photoHeight = delegate.collectionView(collectionView, heightForPhotoAtIndexPath: indexPath)
        let height = cellPadding * 2 + photoHeight
        let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
        let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)

        // 5. Creates an UICollectionViewLayoutItem with the frame and add it to the cache
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        attributes.frame = insetFrame
        cache.append(attributes)

        // 6. Updates the collection view content height
        contentHeight = max(contentHeight, frame.maxY)
        yOffset[column] = yOffset[column] + height

        column = column < (numberOfColumns - 1) ? (column + 1) : 0
    }
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()

    // Loop through the cache and look for items in the rect
    for attributes in cache {
        if attributes.frame.intersects(rect) {
            visibleLayoutAttributes.append(attributes)
        }
    }
    return visibleLayoutAttributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
}

}

1 Ответ

0 голосов
/ 02 августа 2019

Вы должны добавить атрибуты для вашего заголовка, прежде чем добавить первый элемент

Рядом с первым набором yOffset начинается высота вашего заголовка

var yOffset = [yourHeaderHeight, yourHeaderHeight]

Добавьте этот код между разделами после indexPath в разделе 3

 if item == 0 {
                let headerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: indexPath)
                headerAttributes.frame = CGRect(x: 0, y: 0, width: yourHeaderWidth, height: yourHeaderHeight)

                cache.append(headerAttributes)
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...