首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置UICollectionView的UIEdgeInsets

设置UICollectionView的UIEdgeInsets
EN

Stack Overflow用户
提问于 2017-03-04 20:31:11
回答 1查看 1.6K关注 0票数 0

我希望UICollectionView的项目居中,所以我编写了以下代码:

代码语言:javascript
复制
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    let collectionViewWidth = collectionView.bounds.width
    let collectionViewHeight = collectionView.bounds.height
    let numberOfRows = CGFloat(collectionView.numberOfItemsInSection(0))
    let leftValue = (collectionViewWidth / 2.0) - (numberOfRows * 5) - (numberOfRows * (collectionViewHeight / 2.0))
    print(leftValue)
    return UIEdgeInsets(top: 0, left: leftValue, bottom: 0, right: 0)
}

但现在的问题是,我不能滚动到左边,因为我的左边的插图改变,请给我任何解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-16 14:10:49

我通过一些计算和所有的计算得出了这一点,所以代码如下:

代码语言:javascript
复制
func refreshCollectionView(count: Int) {
    let collectionViewHeight = collectionView.bounds.height
    let collectionViewWidth = collectionView.bounds.width
    let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
    if numberOfItemsThatCanInCollectionView > count {
        let totalCellWidth = collectionViewHeight * CGFloat(count)
        let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
        // leftInset, rightInset are the global variables which I am passing to the below function
        leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        rightInset = -leftInset
    } else {
        leftInset = 0.0
        rightInset = -collectionViewHeight
    }
    collectionView.reloadData()
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}

有关更详细的代码,请参阅此处的代码https://github.com/anirudha-music/CollectionViewCenter

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42596046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档