首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有水平插入的集合视图单元格在滚动时不会保持居中

具有水平插入的集合视图单元格在滚动时不会保持居中
EN

Stack Overflow用户
提问于 2017-09-28 19:11:09
回答 2查看 761关注 0票数 1

viewDidLoad中设置如下所示:

代码语言:javascript
运行
复制
func setupCollectionView() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(UINib(nibName: "SubtopicCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SubtopicCollectionCell")
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 16
        collectionView.isPagingEnabled = true
        collectionView.setCollectionViewLayout(flowLayout, animated: false)
    }

不同的委托方法如下:

代码语言:javascript
运行
复制
func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: SubtopicCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubtopicCollectionCell", for: indexPath) as! SubtopicCollectionCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.size.width * 0.78, height: collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
    }

重要的是,下一个单元格的一部分以当前单元格为中心显示在屏幕上(就像演示中的第一个和最后一个单元格一样)。如何实现此行为?

EN

Stack Overflow用户

发布于 2017-09-28 19:31:21

您可以在collectionViewLayout函数中通过以下简单计算来实现。

代码语言:javascript
运行
复制
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    let cellWidth = CellWidth * CellCount
    let spacingWidth = CellSpacing * (CellCount - 1)

    let leftInset = (collectionViewWidth - CGFloat(CellWidth + SpacingWidth)) / 2
    let rightInset = leftInset

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

别忘了实现以下协议

代码语言:javascript
运行
复制
UICollectionViewDelegateFlowLayout
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46467693

复制
相关文章

相似问题

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