You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为attributedPlaceholder设置accessibility标识符以用于UITest?

解决方案

NSAttributedString本身不支持直接设置accessibility标识符,你需要通过承载占位符的UITextField控件的相关属性实现UITest定位需求,两种常用实现方式如下:


方式一:直接给控件设置UITest专属标识(最常用)

accessibilityIdentifier是UIKit专为UITest提供的标识属性,不会被读屏软件读取,不影响普通无障碍功能的使用:

// 1. 定义占位字符串
let placeholderStr = Strings.test
// 2. 赋值富文本占位符
textField.attributedPlaceholder = NSAttributedString(
    string: placeholderStr,
    attributes: [NSAttributedString.Key.foregroundColor: ColorTheme.test]
)
// 3. 设置控件的accessibility标识
textField.accessibilityIdentifier = "test_text_field_placeholder"
// 可选:如果需要直接在UITest里校验占位字符串内容,也可以同步赋值给accessibilityLabel
textField.accessibilityLabel = placeholderStr

UITest侧对应用法:

// 用accessibilityIdentifier定位目标输入框
let testTextField = app.textFields["test_text_field_placeholder"]
// 直接用XCUIElement原生的placeholderValue属性校验占位内容
XCTAssertEqual(testTextField.placeholderValue, Strings.test)

方式二:给富文本占位符加自定义标识

如果需要把标识和富文本本身绑定,你可以自定义富文本属性存储标识,UITest运行时同步到控件的accessibility属性即可:

  1. 先定义自定义富文本key
extension NSAttributedString.Key {
    static let placeholderAccessibilityId = NSAttributedString.Key("PlaceholderAccessibilityId")
}
  1. 创建富文本时加入自定义属性
textField.attributedPlaceholder = NSAttributedString(
    string: Strings.test,
    attributes: [
        .foregroundColor: ColorTheme.test,
        .placeholderAccessibilityId: "test_placeholder_unique_id"
    ]
)
  1. App运行时判断UITest模式,把标识同步到控件属性
#if DEBUG
// 启动UITest时给app传入launchArguments = ["ui_test_running"]即可触发
if ProcessInfo.processInfo.arguments.contains("ui_test_running") {
    if let placeholderId = textField.attributedPlaceholder?.attribute(
        .placeholderAccessibilityId, 
        at: 0, 
        effectiveRange: nil
    ) as? String {
        textField.accessibilityValue = placeholderId
    }
}
#endif

注意事项

  • 优先使用accessibilityIdentifier做UITest定位,避免修改accessibilityLabel、accessibilityValue影响视障用户的读屏体验
  • 不需要额外设置就能直接通过XCUIElement.placeholderValue拿到输入框当前的占位字符串内容,可直接用于内容正确性校验

内容的提问来源于stack exchange,提问作者Straider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 18:00:03