Skip to content

Instantly share code, notes, and snippets.

@jlnquere
Last active June 10, 2022 14:25
Show Gist options
  • Save jlnquere/d2cd529874ca73624eeb7159e3633d0f to your computer and use it in GitHub Desktop.
Save jlnquere/d2cd529874ca73624eeb7159e3633d0f to your computer and use it in GitHub Desktop.
XCUITests: scroll UICollectionView to find one of it's offscreen UICollectionViewCell by id
// Thanks to @MonsieurDart for the idea :)
func scroll(collectionView:XCUIElement, toFindCellWithId identifier:String) -> XCUIElement? {
guard collectionView.elementType == .collectionView else {
fatalError("XCUIElement is not a collectionView.")
}
var reachedTheEnd = false
var allVisibleElements = [String]()
while !reachedTheEnd {
let cell = collectionView.cells[identifier]
// Did we find our cell ?
if cell.exists {
return cell
}
// If not: we store the list of all the elements we've got in the CollectionView
let allElements = collectionView.cells.allElementsBoundByIndex.map({$0.identifier})
// Did we read then end of the CollectionView ?
// i.e: do we have the same elements visible than before scrolling ?
reachedTheEnd = (allElements == allVisibleElements)
allVisibleElements = allElements
// Then, we do a scroll up on the scrollview
let startCoordinate = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.99, dy: 0.9))
startCoordinate.press(forDuration: 0.01, thenDragTo: collectionView.coordinate(withNormalizedOffset:CGVector(dx: 0.99, dy: 0.1)))
}
return nil
}
// After this, you may want to scroll to top ...
func statusBarScrollToTop() {
let statusBar = XCUIApplication().statusBars.element
statusBar.doubleTap()
}
// Sample usage:
if let cell = scroll(collectionView: emojislistCollectionView, toFindCellWithId: "myID") {
cell.tap()
} else {
XCTFail("Unable to find the cell :(")
}
@tomleightonstars
Copy link

hey, the statusBar definition in statusBarScrollToTop no longer works

it needs to be changed to

let statusBar = XCUIApplication(bundleIdentifier: "com.apple.springboard").statusBars.element(boundBy: 1)
statusBar.tap()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment