如何在Swift中给文本框设置ID?Xcode配置控件标识符用于Appium自动化
Hey there! Great call asking about this—setting unique identifiers for your UI elements is totally feasible (and essential) for Appium automation, just like you noticed with inspectable apps. Let’s break down the two main ways to do this:
1. Visual Setup via Storyboard/XIB
If you’re using Interface Builder to build your UI, this is the quickest method:
- Open your Storyboard or XIB file, then select the text field or button you want to tag.
- Switch to the Identity Inspector (the third tab in the right sidebar, looks like a small ID card icon).
- Scroll down to the Accessibility section, then enter a unique, descriptive name in the Identifier field (e.g.,
loginEmailTextFieldorsignUpSubmitButton).Pro tip: Stick to a consistent naming convention—this will make writing your Appium test scripts way smoother later on.
2. Programmatic Setup in Swift
If you’re creating UI elements entirely in code, set the identifier directly using the accessibilityIdentifier property:
// For a text field let passwordTextField = UITextField(frame: CGRect(x: 20, y: 150, width: 320, height: 44)) passwordTextField.accessibilityIdentifier = "loginPasswordTextField" view.addSubview(passwordTextField) // For a button let resetPasswordButton = UIButton(type: .system) resetPasswordButton.setTitle("Reset Password", for: .normal) resetPasswordButton.frame = CGRect(x: 20, y: 210, width: 320, height: 44) resetPasswordButton.accessibilityIdentifier = "resetPasswordButton" view.addSubview(resetPasswordButton)
This accessibilityIdentifier is exactly what Appium uses to locate your elements—think of it as the official "automation ID" for your controls.
Quick Appium Test Example
Once you’ve set these identifiers, you can reference them in your tests with locator strategies like this (using Java as an example):
MobileElement passwordField = driver.findElement(MobileBy.AccessibilityId("loginPasswordTextField"));
内容的提问来源于stack exchange,提问作者Matheus Marques

