Swift中ForEach创建的TextField无法触发.onKeyPress问题求助
解决SwiftUI中OTP TextField删除键切换焦点问题
你可以通过**当前聚焦的索引(即OTPFocused的值)**定位触发删除键的TextField,从而实现按删除键切换到上一个输入框的逻辑。具体修改方案如下:
修改后的代码
ForEach(0..<6) { index in TextField("", text: $OTPStringArray[index]) .frame(width: 45, height: 48) .background(Color.gray.opacity(0.5)) .cornerRadius(8) .multilineTextAlignment(.center) .focused($OTPFocused, equals: index) .tag(index) .keyboardType(.default) .onKeyPress(.delete) { // 获取当前聚焦的输入框索引 guard let currentIndex = OTPFocused else { return .ignored } if currentIndex > 0 && OTPStringArray[currentIndex].isEmpty { // 当前输入框为空时,切换到上一个并清空内容(按需调整) OTPStringArray[currentIndex - 1] = "" OTPFocused = currentIndex - 1 } else { // 当前输入框有内容时,仅清空当前 OTPStringArray[currentIndex] = "" } return .handled // 阻止系统默认删除行为 } .onChange(of: OTPStringArray[index]) { oldValue, newValue in if newValue.count > 1 { OTPStringArray[index] = String(newValue.suffix(1)) } // 仅在从空输入变为非空时,切换到下一个输入框 if !newValue.isEmpty && oldValue.isEmpty { if index < 5 { OTPFocused = index + 1 } else { pagingIndex = 7 } } } }
关键逻辑说明
- 通过
OTPFocused定位当前输入框:focused($OTPFocused, equals: index)已经将当前聚焦的索引绑定到OTPFocused,所以在onKeyPress中可以直接获取触发删除操作的TextField索引。 - 区分删除键行为:
- 若当前输入框为空,按删除键则切换到上一个输入框,可按需清空上一个输入框的内容;
- 若当前输入框有内容,按删除键仅清空当前输入框,不切换焦点。
- 避免逻辑冲突:修改
onChange的触发条件,仅在输入框从空变为非空时切换到下一个输入框,防止删除操作触发不必要的焦点跳转。
内容的提问来源于stack exchange,提问作者Mr. Man
相关产品推荐
相关产品推荐

