首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >swift:滚动collectionView

swift:滚动collectionView
EN

Stack Overflow用户
提问于 2018-07-18 08:23:35
回答 3查看 220关注 0票数 1

我有collectionView,我想滚动到下一部分按钮点击。怎么做?

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

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

@IBAction func nextAction(_ sender: Any) {
        //scroll to next
    }

更新

代码语言:javascript
复制
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        cellOffset = 10

        cellWidth = (collectionView.bounds.width / 3)  - (cellOffset * 4)
        cellHeight = (cellWidth / 2 * 3) + (cellWidth / 2 * 0.65)

        return CGSize(width: cellWidth, height: cellHeight)
    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-07-18 08:32:33

这可以通过一些简单的步骤来完成:

  • 查找当前可见的第一个区段的节号。
  • 如果区段号不是最后一节,则向其中添加1。
  • 滚动到具有新节号的区段。 设currentlyVisibleSection = collectionView.indexPathsForVisibleItems.map {$0.节}.min()!如果currentlyVisibleSection <3{让scrollToSection = currentlyVisibleSection +1 collectionView.scrollToItem(at: IndexPath(项目: 0,节: scrollToSection),at:.top,动画:真)}}
票数 0
EN

Stack Overflow用户

发布于 2018-07-18 08:31:08

假设您有一个跟踪当前滚动部分的变量。

代码语言:javascript
复制
@IBAction func nextAction(_ sender: Any) {

    let attr = collectionView.layoutAttributesForItem(at: IndexPath.init(row: 0, section: currentSection))
    collectionView.setContentOffset(attr!.frame.origin, animated: true)
    currentSection += 1;
    if currentSection >= maxSectionCount {
        currentSection = maxSectionCount - 1
    }
}
票数 0
EN

Stack Overflow用户

发布于 2018-07-18 08:41:54

代码语言:javascript
复制
func goToNextSection() {
    guard let nextIndex = getNextSectionIndex() else {
        return
    }
    goToItemAt(nextIndex)
}

func getNextSectionIndex() -> IndexPath? {
    guard let firstVisibleCell = mycollection.visibleCells.first, // maybe last in your scenario
        let indexOfFirstCell = mycollection.indexPath(for: firstVisibleCell) else {
        return nil
    }
    let nextIndex = IndexPath(item: 0, section: indexOfFirstCell.section + 1)
    let yesIhaveCellsHere = true // you need to check if your DS has 'cells' for this, otherwise it will crash at scroll to item
    guard yesIhaveCellsHere else {
        return nil
    }
    return nextIndex
}

func goToItemAt(_ index: IndexPath) {
    mycollection.scrollToItem(at: index,
                              at: UICollectionViewScrollPosition.left, // adjust for your scenario
                              animated: true)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51397031

复制
相关文章

相似问题

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