通过 FocusState 修饰键盘消失state
struct ContentView: View {
@State private var name = ""
@FocusState private var nameIsFocused: Bool
var body: some View {
TextField("input user name", text: $name).focused($nameIsFocused)
Button("Submit"){
nameIsFocused = false
}
}
}
高级用法通过绑定输入框类型动态调整焦点
struct ContentView: View {
enum Field {
case username
case password
case confirmedPassword
}
@State private var username = ""
@State private var password = ""
@FocusState private var focusedField: Field?
var body: some View {
VStack {
TextField("username", text: $username)
.focused($focusedField, equals: .username)
.textContentType(.givenName)
.submitLabel(.next)
TextField("password", text: $password)
.focused($focusedField, equals: .password)
.textContentType(.password)
.submitLabel(.next)
TextField("confirmed password", text: $password)
.focused($focusedField, equals: .confirmedPassword)
.textContentType(.password)
.submitLabel(.next)
Button("signup") {
hideKeyboard()
}
}
.onSubmit {
// 点击键盘的next 调用 onSubmit
print("focusedField:\(String(describing: focusedField))")
switch focusedField {
case .username:
focusedField = .password
case .password:
focusedField = .confirmedPassword
default:
hideKeyboard()
}
}
}
}
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
网友评论