为什么没有调用UICollectionView insetForSectionsAtIndex?

时间:2017-03-30 09:40:24

标签: swift uicollectionview

我希望使用以下功能,但不幸的是它没有被调用。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlowLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let cellCount = Double(collectionView.numberOfItems(inSection: section))
        if let cell = collectionView.cellForItem(at: IndexPath(row: 0, section: section))
        {
            let cellWidth = Double(cell.frame.size.width)
            let totalCellWidth = cellWidth * cellCount
            let cellSpacing = Double(collectionViewLayout.minimumInteritemSpacing)
            let totalSpacingWidth = cellSpacing * (cellCount - 1)

            let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
            let rightInset = leftInset

            return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
        }

    return collectionView.layoutMargins
}

我收到以下控制台错误,但我的单元格小于我的collectionView,并且我将section insets和layout margin设置为0。

  

2017-03-30 11:25:14.624 Prep [92400:1862856]未定义UICollectionViewFlowLayout的行为,因为:   2017-03-30 11:25:14.624 Prep [92400:1862856]项目高度必须小于UICollectionView的高度减去截面插入顶部和底部值,减去内容插入顶部和底部值。   2017-03-30 11:25:14.624 Prep [92400:1862856]相关的UICollectionViewFlowLayout实例是,它被附加到; layer =; contentOffset:{0,0}; contentSize:{0,68.5}>集合视图布局:。   2017-03-30 11:25:14.625 Prep [92400:1862856]在UICollectionViewFlowLayoutBreakForInvalidSizes上创建一个符号断点,以便在调试器中捕获它。    细胞高度 - > 42.0

enter image description here

协议

class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?

class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?

enter image description here

1 个答案:

答案 0 :(得分:1)

好的,没有调用insetForSectionAt的问题是你必须像这样实现它:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

   //access to minimumInteritemSpacing by casting to UICollectionViewFlowLayout
   let layout = collectionViewLayout as! UICollectionViewFlowLayout
   let spacing = layout.minimumInteritemSpacing       

   return UIEdgeInsetsMake(0.5,0,0.5,0)

}

看看UICollectionViewDelegateFlowLayout协议。 insetForSectionAt声明如下:

@available(iOS 6.0, *)
optional public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets

所以你需要第一个可选参数来实现这个功能。