P. Pawluś P. Pawluś - 4 months ago 34
Swift Question

Place cursor at the end of UITextView under UITest

This is how I clear

UITextFields
and
UITextViews
in UITests.

extension XCUIElement {

func clear() {

tap()

while (value as! String).characters.count > 0 {
XCUIApplication().keys["delete"].tap()
}
}
}


Example of use:

descriptionTextView.type("Something about Room.")
descriptionTextView.clear()


If I run UITests, it always tap at the beginning of UITextView.

How to tap at the end?

Answer

You can tap on the lower right corner to place the cursor at the end of the text view.

Additionally you can improve the speed of deletion by preparing a deleteString containing a number of XCUIKeyboardKeyDelete that wipes your entire text field at once.

extension XCUIElement {
   func clear() {
      guard let stringValue = self.value as? String else {
          XCTFail("Tried to clear and enter text into a non string value")
          return
      }

      let lowerRightCorner = self.coordinateWithNormalizedOffset(CGVectorMake(0.9, 0.9))
      lowerRightCorner.tap()

      let deleteString = [String](count: stringValue.characters.count + 1, repeatedValue: XCUIKeyboardKeyDelete)
      self.typeText(deleteString.joinWithSeparator(""))
   }
}