Xcode UITesting - 如何移动 UISlider?

Xcode UITesting - how to move UISlider?

有没有办法将 UISlider 移动到 Xcode 中的 UITests 目标下?我真的需要将它从代码中移走。可能吗?

  1. 获取滑块:

    let app = XCUIApplication()
    let timeSlider = app.sliders["timeSlider"]
    
  2. 调整其值:

    timeSlider.adjustToNormalizedSliderPosition(0.9)
    

我无法让 adjustToNormalizedSliderPosition 使用我的应用程序的滑块。我看到有些人在网上发帖说它对他们也不起作用。 它对这里的其他人有用吗?

一个不太有用的调整滑块的方法是找到元素,按住一段时间,然后拖动到另一个元素:

slider.pressForDuration(duration: 0.05, thenDragToElement: anotherElement)

我根据 的回答做了这个扩展来解决 adjustToNormalizedSliderPosition 问题。

import XCTest

extension XCUIElement {

    open func adjust(toNormalizedSliderValue normalizedSliderValue: CGFloat) {
        let start = coordinate(withNormalizedOffset: CGVector(dx: 0.0, dy: 0.0))
        let end = coordinate(withNormalizedOffset: CGVector(dx: normalizedSliderValue, dy: 0.0))
        start.press(forDuration: 0.05, thenDragTo: end)
    }

}

那么你只需要调用:

app.sliders["Your Slider Identifier"].adjust(toNormalizedSliderValue: 0.5)

在这里您可以找到 Xcode UITesting 的一些其他有用技巧:

https://github.com/joemasilotti/UI-Testing-Cheat-Sheet