2017-08-10 46 views
0

我使用两个补充视图(即,UICollectionReusableView s)来渲染页脚和页眉夹着UICollectionView。UICollectionViewController:使粘页脚,无论CollectionView的大小如何

问题是,当UICollectionView短(例如,只有一个单元格被占用)时,页脚视图向上滑动,并且不会“粘”到底部!

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

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

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

回答

0

如果你没有坚持使用UICollectionViewController,我通常使用普通的'ol UIViewController并在其中粘贴一个UICollectionView,从而扩展UICollectionViewDataSource和UICollectionViewDelegate协议。

我想如果你需要UICollectionViewController,你可以做同样的事情,但嵌入视图控制器本身。

使用UIViewController可以轻松地将视图粘贴到需要约束的位置。

+0

我们最终可能会按照你的建议。我之所以选择带有UICollectionViewController的“内置”页脚/标题是因为它是开箱即用的,该控制器对我们的问题很好。我认为一个通用的UIViewController可能会正常工作,但可能需要更多的脚步工作... –

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) 

}} 
+0

将class StickyFooter分配给您的collectionviewflow布局 –