如何让UIControl在XCUITest中显示为按钮?

时间:2016-12-09 11:46:21

标签: ios xcode-ui-testing

我创建了一个UIControl的子类,其行为与UIButton类似。

当我使用XCUITest运行UI测试时,按钮显示在XCUIApplication().staticTexts而不是预期的XCUIApplication().buttons

1 个答案:

答案 0 :(得分:5)

在打猎之后,我发现这是由于未设置的可访问性特征。例如,如果我有以下类;

class ActivityButton: UIControl {

    private let activityIndicator: UIActivityIndicatorView = {
        let activityIndicator = UIActivityIndicatorView()
        activityIndicator.hidesWhenStopped = true
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        return activityIndicator
    }()

    let titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        return titleLabel
    }()

    override public init(frame: CGRect) {
        super.init(frame: frame)
        // This is the required call to make the control appear 
        // as a button in ui tests
        accessibilityTraits = UIAccessibilityTraitButton
        addSubview(activityIndicator)
        addSubview(titleLabel)
        createConstraints()
    }    

}