SwiftUI:为TextField添加键盘工具栏按钮实现文本自动补全
实现SwiftUI邮箱输入框的自定义后缀补全
方案一:键盘工具栏按钮补全
直接基于你现有的工具栏思路扩展,把常用邮箱后缀做成数组循环生成按钮,点击时自动追加到输入框:
// 定义常用邮箱后缀数组 private let emailSuffixes = ["@gmail.com", "@yahoo.com", "@outlook.com", "@icloud.com"] private var emailSection: some View { Section { HStack { UVFloatingTextField(title: "E-Mail", text: $email, keyboardType: .emailAddress) .toolbar { ToolbarItemGroup(placement: .keyboard) { // 循环生成后缀按钮 ForEach(emailSuffixes, id: \.self) { suffix in Button(suffix) { // 追加后缀到输入框 email += suffix } } Spacer() Button("Done") { isInputActive = false } } } if email.isEmpty { MandatoryInfo() } } } header: { Text("Angaben zur E-Mail") .sectionHeader() } }
这个方案改动最小,完全复用你现有的布局,新增后缀只需要在数组里添加即可。
方案二:自定义自动补全弹窗(更友好的体验)
如果想要更智能的补全效果,可以在用户输入@后自动展示匹配的后缀列表,点击直接补全:
@State private var email: String = "" // 存储匹配的后缀建议 @State private var suggestedSuffixes: [String] = [] private let emailSuffixes = ["@gmail.com", "@yahoo.com", "@outlook.com", "@icloud.com"] private var emailSection: some View { Section { VStack(alignment: .leading, spacing: 8) { HStack { UVFloatingTextField(title: "E-Mail", text: $email, keyboardType: .emailAddress) .onChange(of: email) { newValue in // 当输入包含@但未输完后缀时,筛选匹配建议 if newValue.contains("@"), let atIndex = newValue.firstIndex(of: "@") { let prefixAfterAt = String(newValue[newValue.index(after: atIndex)...]) suggestedSuffixes = emailSuffixes.filter { $0.hasPrefix("@\(prefixAfterAt)") } } else { suggestedSuffixes = [] } } if email.isEmpty { MandatoryInfo() } } // 显示补全建议列表 if !suggestedSuffixes.isEmpty { LazyVStack(spacing: 0) { ForEach(suggestedSuffixes, id: \.self) { suffix in Button(action: { // 替换当前输入的后缀部分为完整后缀 if let atIndex = email.firstIndex(of: "@") { email = String(email[..<atIndex]) + suffix } else { email += suffix } }) { Text(suffix) .padding(.vertical, 8) .padding(.horizontal, 12) .frame(maxWidth: .infinity, alignment: .leading) } .border(.gray.opacity(0.2), edge: .bottom) } } .background(.white) .cornerRadius(8) .shadow(color: .black.opacity(0.1), radius: 4, x: 0, y: 2) } } } header: { Text("Angaben zur E-Mail") .sectionHeader() } }
逻辑说明
- 监听输入框内容变化,当用户输入@后,自动筛选出匹配的后缀建议
- 点击建议项时,会自动替换输入框中不完整的后缀部分,直接生成完整邮箱地址
- 这种方式更贴近原生APP的交互体验,用户操作更高效
方案三:优化细节:禁用系统自动纠正
如果系统自动纠正影响自定义补全,可以给输入框添加禁用配置:
UVFloatingTextField(title: "E-Mail", text: $email, keyboardType: .emailAddress) .autocorrectionDisabled(true) // 禁用系统自动纠正 .onChange(of: email) { newValue in // 补全逻辑... }
内容的提问来源于stack exchange,提问作者ufuk
相关产品推荐
相关产品推荐

