本文把“TextInput”作为便于检索的分类名称:用于配置 TextField、SecureField 和 TextEditor 等文本输入控件的行为,而不是某一个独立控件。
需要完整、随 SDK 更新的说明时,优先查看 Apple 的文本输入与输出总览,以及 TextField、SecureField 和 TextEditor 的官方文档。
常用修饰器#
| 修饰器 | 用途 | 常见场景 |
|---|---|---|
keyboardType(_:) | 选择更合适的软键盘布局 | 邮箱、URL、数字、电话号码 |
textInputAutocapitalization(_:) | 设置自动大写策略 | 姓名用 .words;邮箱、用户名、验证码用 .never |
autocorrectionDisabled(_:) | 关闭自动纠错 | 邮箱、账号、代码、验证码 |
textContentType(_:) | 声明输入内容的语义,帮助系统提供建议或自动填充 | .emailAddress、.username、.password、.oneTimeCode |
submitLabel(_:) + onSubmit(of:_:) | 设置提交键语义并处理提交事件 | .next、.done、.search |
focused(_:equals:) | 管理多输入框焦点 | 在“下一项”和“完成”之间切换焦点 |
简单示例#
以下示例面向 iOS/iPadOS 的邮箱输入:
TextField("邮箱", text: $email)
.keyboardType(.emailAddress)
.textContentType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.submitLabel(.done)
.onSubmit {
submit()
}注意事项#
keyboardType(_:)只是在改善输入体验,不会替代格式或服务端校验。textContentType(_:)提供语义和自动填充线索;密码仍应使用SecureField。- 不同控件和平台的可用性并不完全一致,尤其是键盘相关行为;最终以对应 Apple API 页的 availability 为准。
- 新代码应使用
textInputAutocapitalization(_:)与autocorrectionDisabled(_:),避免旧的自动大写与自动纠错 API。