UICollectionViewController:制作粘性页脚,不管CollectionView的大小

时间:2017-08-10 23:27:41

标签: ios swift3

我正在使用两个补充视图(即UICollectionReusableView s)来呈现将UICollectionView夹在中间的页脚和标题。'

问题是,当UICollectionView很短(例如,只占用一个单元格)时,页脚视图会向上滑动,而不会“粘贴”#34;到底!

其他文章已经解决了这种行为;在某些情况下,作者使用自定义布局来实现粘性页脚/标题。相反,我只是将sectionFootersPinToVisibleBoundssectionHeadersPinToVisibleBounds设置为true,这通常可以正常工作 - 直到UICollectionView很短。

这发生在Swift 3.0(iOS 10.3),iPhone 6.x模拟器中。

将页脚视图固定到UICollectionViewController底部的建议方法是什么?

1 个答案:

答案 0 :(得分:0)

好..所以我尝试从下面链接更新代码。它有效。

https://teamtreehouse.com/community/add-sticky-footer-to-uicollectionview-in-swift

class StickyFooter : UICollectionViewFlowLayout {


var footerIsFound             : Bool = false
var UICollectionAttributes    : [UICollectionViewLayoutAttributes]?


override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
    return true
}


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

    for  attributes in UICollectionAttributes! {

        if let type = attributes.representedElementKind {

            if type == UICollectionElementKindSectionFooter
            {
                footerIsFound = true
                updateFooter(attributes: attributes)
            }
        }
    }

    if (!self.footerIsFound) {

        let newItem = self.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionFooter, at : NSIndexPath(row: self.UICollectionAttributes!.count, section: 0) as IndexPath)


        UICollectionAttributes?.append(newItem!)

    }

    return UICollectionAttributes
}

override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
{
    let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)

    attributes.size = CGSize(width: self.collectionView!.bounds.size.width, height: 75) //your footer size

    if elementKind.isEqualToString(find: UICollectionElementKindSectionFooter)
    {
        updateFooter(attributes: attributes)
    }
    return attributes
}

func updateFooter(attributes : UICollectionViewLayoutAttributes){
    let currentBounds = self.collectionView?.bounds
    attributes.zIndex = 1024
    attributes.isHidden = false
    let yOffset = currentBounds!.origin.y + currentBounds!.size.height - attributes.size.height/2.0
    attributes.center = CGPoint(x: currentBounds!.midX, y: yOffset)

}}