14

Is there a way to move UISlider under UITests target in Xcode? I really need to move it from code. Is it possible?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

5 Answers5

19
  1. Get your slider:

    let app = XCUIApplication()
    let timeSlider = app.sliders["timeSlider"]
    
  2. Adjust its value:

    timeSlider.adjustToNormalizedSliderPosition(0.9)
    
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
3

I made this extension based on this answer to fix the adjustToNormalizedSliderPosition problem.

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)
    }

}

Then you only have to call instead:

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

Here you can find some other useful tips for Xcode UITesting:

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

odm
  • 888
  • 1
  • 14
  • 22
0

I wasn't able to get adjustToNormalizedSliderPosition to work with my app's slider. I've seen some people posting online that it also didn't work for them. Is it working for others here?

A less useful method to adjust a slider is to find the element, press for a duration, then drag to another element:

slider.pressForDuration(duration: 0.05, thenDragToElement: anotherElement)
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
DonoCork
  • 13
  • 3
  • Hm. I verified that I did in fact have an accessibilityIdentifier set for the slider, but was still unable to adjust the slider using your posted solution. Any other ideas of what could be going wrong for me? I'm able to successfully locate the element by accessibilityIdentifier and perform other actions on it, just not `adjustToNormalizedSliderPosition`. – DonoCork Feb 18 '16 at 20:00
0

Swift 4.2+

@bartłomiej-semańczyk answer, modified a little bit like this:

  1. Get your slider:
    let app = XCUIApplication()
    let timeSlider = app.sliders["timeSlider"]
  1. Adjust its value:
    timeSlider.adjust(toNormalizedSliderPosition: 0.9)

Note: The number is CGFloat and it is between 0 and 1. If your UISlider minimum and maximum value is not 0 to 1 you have to convert it first like this:

    let numberBetween01 = CGFloat((requestedVal - UISlider.minimumValue ) / UISlider.maximumValue - UISlider.minimumValue))
Esmaeil
  • 558
  • 5
  • 11
0

How to move UISlider to Right ➡️

  static func moveSliderToRight(element: XCUIElement){
  _ =  element.waitForExistence(timeout: 10)
    element.adjust(toNormalizedSliderPosition: 1)
}

How to move UISlider to Left ⬅️

  static func moveSliderToRight(element: XCUIElement){
  _ =  element.waitForExistence(timeout: 10)
    element.adjust(toNormalizedSliderPosition: 0)
}
Bayram Binbir
  • 1,531
  • 11
  • 11