4

I downloaded this Pintrest-esc Custom Layout for my CollectionView from : https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2 (modified it a little bit to do with cache code)

So the layout works fine, i got it set up so when you scroll to the bottom, i make another API call, create and populate additional cells.

Problem: If a User scrolls down and loads some more cells (lets say 20 for example) and then uses the "Search Feature" i have implemented at the top, it will then filter some of the data via price from MinRange - MaxRange leaving you with (lets say 5 results), thus deleting some cells and repopulating those. BUT - All that space and scrollable space that existed for the first 20 cells still exists as blank white space.... How can i remove this space ? and why can it resize when adding more cells, but not when removing them ?

Code of my API Call:

DispatchQueue.global(qos: .background).async {

        WebserviceController.GetSearchPage(parameters: params) { (success, data) in
            if success
            {

                if let products = data!["MESSAGE"] as? [[String : AnyObject]]
                {
                    self.productList = products

                }
            }

            DispatchQueue.main.async(execute: { () -> Void in
                self.pintrestCollectionView.reloadData()
          self.pintrestCollectionView.collectionViewLayout.invalidateLayout()
                self.pintrestCollectionView.layoutSubviews()
            })

        }

    }

Code Of Custom Layout Class & protocol:

protocol PinterestLayoutDelegate: class {

func collectionView(_ collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat

}

class PintrestLayout: UICollectionViewFlowLayout {

// 1

weak var delegate : PinterestLayoutDelegate!

// 2
fileprivate var numberOfColumns = 2
fileprivate var cellPadding: CGFloat = 10

// 3
fileprivate var cache = [UICollectionViewLayoutAttributes]()

// 4
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)
}

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

override func prepare() {
    // 1
    //You only calculate the layout attributes if cache is empty and the collection view exists.
    /*guard cache.isEmpty == true, let collectionView = collectionView else {
        return
    }*/
    cache.removeAll()
    guard cache.isEmpty == true || cache.isEmpty == false, let collectionView = collectionView else {
        return
    }
    // 2
    //This declares and fills the xOffset array with the x-coordinate for every column based on the column widths. The yOffset array tracks the y-position for every 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
    //This loops through all the items in the first section, as this particular layout has only one section.
    for item in 0 ..< collectionView.numberOfItems(inSection: 0) {

        if collectionView.numberOfItems(inSection: 0) < 3
        {
            collectionView.isScrollEnabled = false
        } else {
            collectionView.isScrollEnabled = true
        }

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

        // 4
        //This is where you perform the frame calculation. width is the previously calculated cellWidth, with the padding between cells removed.

        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: 7, dy: 4)

        collectionView.contentInset = UIEdgeInsets.init(top: 15, left: 12, bottom: 0, right: 12)

        // 5
        //This creates an instance of UICollectionViewLayoutAttribute, sets its frame using insetFrame and appends the attributes to cache.
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        attributes.frame = insetFrame
        cache.append(attributes)

        // 6
        //This expands contentHeight to account for the frame of the newly calculated item.
        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
}

FYI: In MainStoryboard, i disabled "Adjust Scroll View Insets" as many of other threads and forums have suggested...

amirkrd
  • 203
  • 3
  • 8

1 Answers1

5

I'm guessing you've already found the answer, but I'm posting here for the next person since I ran into this issue.

The trick here is contentHeight actually never gets smaller.

contentHeight = max(contentHeight, frame.maxY)

This is a nondecreasing function.

To fix it, just set contentHeight to 0 if prepare is called:

guard cache.isEmpty == true || cache.isEmpty == false, let 
  collectionView = collectionView else {
    return
}
contentHeight = 0
Nathan
  • 76
  • 1
  • 7