UITest - 当 isPagingEnabled true 时,UICollectionView 水平方向滚动问题

问题描述 投票:0回答:1

UICollectionView
属性设置为
isPagingEnabled
时,我一直尝试通过水平滚动将
true
滚动到下一页。我已经研究了几天并且做了很多研究,但我找不到像我这样的案例。如果您已经遇到了这个问题并且已经找到了解决方案,那么与我分享您的解决方案将会很棒。这是我目前的案例;

func sampleTest() {
    let collectionView = app.collectionViews[.sampleCollectionView]
    collectionView.waitUntil(.exists)
    let totalPageCount = collectionView.cells.count
    guard totalPageCount > 0 else {
        XCTFail("No pages could find in collection to take snapshot.")
        return
    }
    for currentPage in 1...totalPageCount {
        snapshot("Page\(currentPage)")
        collectionView.swipeLeft()
    }
}

在这里,

swipeLeft()
XCUIElement
方法在我的例子中没有按预期工作。当我调用该方法时,它不会移动到下一页。由于
isPagingEnabled = true
声明,它稍微滑动了一下并返回。

此外,还有一个问题是

collectionView.cells.count
计算错误。它总是返回 1。我认为问题的原因与可重用性有关。因为其他单元尚未出队。或者
collectionView.cells.count
没有像我想象的那样工作?

ios swift uicollectionview xcode-ui-testing
1个回答
0
投票

我遇到了类似的问题,分页在我的 UI 测试中表现不佳,因为我的第一个单元格有左侧内容插入并且居中,而下一个单元格总是窥视视图,因此按边界的大小滚动collectionView 没有给出预期的结果。

相反,我在 collectionView 上禁用了

isPagingEnabled
并使用这些
UIScrollViewDelegate
方法“捕捉”到要显示的下一个单元格的中心,具体取决于用户(或测试)滑动的方式:

var collectionViewContentOffsetXBeforeScrolling: CGFloat = 0.0

记录开始减速时的内容偏移:

func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
  guard scrollView == collectionView else { return }
  collectionViewContentOffsetXBeforeScrolling = scrollView.contentOffset.x
}

将当前视图中最左边或最右边的单元格居中:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  if scrollView == collectionView {
  
    let visibleIndexPaths = collectionView.indexPathsForVisibleItems.sorted(by: { $0.item < $1.item })
  
    if let rightMostCell = visibleIndexPaths.last, let leftMostCell = visibleIndexPaths.first {
      let indexPathToSelect = collectionView.contentOffset.x > collectionViewContentOffsetXBeforeScrolling ? rightMostCell: leftMostCell
    
      let cellToBeCentered = collectionView.cellForItem(at: indexPathToSelect)
      collectionView.scrollToItem(at: indexPathToSelect, at: .centeredHorizontally, animated: true)
  }
}

最后,我设置

bounces = false
来简化逻辑并防止在 collectionView 单元格的任一端调用该方法时出现错误行为。

© www.soinside.com 2019 - 2024. All rights reserved.