Swift UI测试,如何检查单元格是否有一个ImageView。

3
在UI测试中,我可以使用以下代码获取第一个单元格:
let app = XCUIApplication()

app.launch()

let tablesQuery = app.tables

let cell = tablesQuery.children(matching:.any).element(boundBy: 0)

如何检查是否在单元格中包含ImageView?
5个回答

2

Swift 5

首先在故事板或ViewDidLoad中为单元格的ImageView设置可访问标识符

Storyboard Accessibility ID

func testIsImageViewNil() {
    let imageView = app.images["PhotosCollectionViewController.ImageCell.ImageView"]
    XCTAssertNotNil(imageView)
}

1
public func hasImageViewInside(_ cell: UITableViewCell) -> Bool {
    for child in cell.subviews {
        if let _ = child as? UIImageView {
            return true
        }
    }
    return false
}

如果imageView的层级超过一层,这段代码就行不通了。很可能是因为imageView没有正确地添加到cell.contentView中。 - Connor Neville
@ConnorNeville 你说得对,但是把它变成递归形式也不太难。思路是一样的。 - sdasdadas
1
在 UI 测试中查询时,您无法访问此内容,对吗? - Thermometer

0
cell.images.element.assert(\.exists)

你可以使用这个图像视图的XCUIElement来做你想要的事情,而不是使用.assert(\.exists)


0
        for viw in cell.contentView.subviews {
        if ((viw as? UIImageView) != nil) {
            print("123")
        }
    }

-1
  for case let imageView as UIImageView in cell.contentView.subviews  {
      if imageView.tag == 1001 {
         imageView.image = UIImage(named: "myCustomImage")
      }
  }

  //OR Altervnatively


  cell.contentView.subviews.flatMap { $0 as? UIImageView }.forEach { imageView in
      if imageView.tag == 1001 {
         imageView.image = UIImage(named: "myCustomImage")
      }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接