将光标放在 UITest 下 UITextView 的末尾

Place cursor at the end of UITextView under UITest

这就是我在 UITests 中清除 UITextFieldsUITextViews 的方式。

extension XCUIElement {

   func clear() {

      tap()

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

使用示例:

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

如果我 运行 UITests,它总是在 UITextView 的开头点击。

最后怎么点击?

您可以点击右下角的 将光标置于文本视图的末尾。

此外,您可以通过准备一个包含多个 XCUIKeyboardKeyDeletedeleteString 来提高删除速度,该 XCUIKeyboardKeyDelete 可以一次擦除整个文本字段。

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

这是 Tomas Camin 的解决方案,适用于 Swift 5.3 (Xcode 12):

extension XCUIElement {
    public 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.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.9))
        lowerRightCorner.tap()

        let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: stringValue.count)
        self.typeText(deleteString)
    }
}