UITest问题:isPagingEnabled为true时UICollectionView水平滚动异常
UITest分页UICollectionView的翻页与计数问题解决方案
我之前做UITest时也碰到过一模一样的分页UICollectionView坑,折腾了好几天才理顺,分享下我的解决思路:
问题1:swipeLeft()触发分页失败(滑动后回弹)
系统自带的swipeLeft()方法滑动幅度偏小,对于开启isPagingEnabled的UICollectionView来说,这个幅度往往达不到分页切换的阈值,所以会出现滑动后立即回弹的情况。
解决办法是自定义一个长距离滑动方法,通过元素坐标点实现足够幅度的滑动:
extension XCUIElement { func customSwipeLeft() { // 从元素右侧90%位置拖动到左侧10%位置,保证滑动幅度足够触发分页 let startCoord = self.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)) let endCoord = self.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.5)) startCoord.press(forDuration: 0.1, thenDragTo: endCoord) } }
把你代码里的collectionView.swipeLeft()替换成collectionView.customSwipeLeft(),就能正常触发分页切换了。
问题2:collectionView.cells.count始终返回1
这个确实和cell复用机制有关——UITest只能检测到当前屏幕上可见的cell,未出列的复用cell不会被统计,所以会一直返回1。
要获取准确的总页数,最可靠的方式是在App代码里把总页数暴露给UITest:
- 在UICollectionView所在的ViewController中,设置accessibilityValue为总页数:
// 假设你的总页数变量是totalPages collectionView.accessibilityValue = "\(totalPages)"
- 在UITest中读取这个值并调整逻辑:
func sampleTest() { let collectionView = app.collectionViews[.sampleCollectionView] collectionView.waitUntil(.exists) // 从accessibilityValue解析总页数 guard let totalPageCountString = collectionView.value as? String, let totalPageCount = Int(totalPageCountString), totalPageCount > 0 else { XCTFail("No pages could find in collection to take snapshot.") return } for currentPage in 1...totalPageCount { snapshot("Page\(currentPage)") // 最后一页无需滑动 if currentPage < totalPageCount { collectionView.customSwipeLeft() // 等待页面切换完成,避免快照时机错误 collectionView.waitForExistence(timeout: 1.0) } } }
也可以通过循环滑动直到无法再滑动的方式统计页数,但这种方法稳定性较差(比如遇到加载延迟会出错),不如直接传递总页数可靠。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

