textFieldDidBeginEditing and textFieldDidEndEditing in SwiftUI

jsb*_*eJS 2 ios swift swiftui

how can I use the methods textFieldDidBeginEditing and textFieldDidEndEditing with the default TextField struct by apple.

Dav*_* B. 12

SwiftUI 3(iOS 15+)

由于 TextField.init(_text:onEditingChanged:) 计划在未来版本中弃用,因此最好使用 @FocusState。此方法还有一个额外的好处,即知道 TextField 何时不再是“第一响应者”,.onChange(of:).onSubmit(of:)单独使用此方法是行不通的。

@State private var text = ""
@FocusState private var isTextFieldFocused: Bool
    
    var body: some View {
        TextField("Text Field", text: $text)
            .focused($isTextFieldFocused)
            .onChange(of: isTextFieldFocused) { isFocused in
                if isFocused {
                    // began editing...
                } else {
                    // ended editing...
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)


RPa*_*l99 7

TextField具有onEditingChangedonCommit回调。

例如:

@State var text = ""
@State var text2 = "default"
var body: some View {
    VStack {
        TextField($text, placeholder: nil, onEditingChanged: { (changed) in
            self.text2 = "Editing Changed"
        }) {
            self.text2 = "Editing Commited"
        }
        Text(text2)
    }
}
Run Code Online (Sandbox Code Playgroud)

onEditingChanged仅当用户选择时才调用in中的代码textField,并且onCommit仅在点击返回,完成等时才调用。

编辑:当用户从一个更改TextField为另一个时,先前选择TextField的会onEditingChanged被调用一次,changed参数()等于false,刚选择TextFieldonEditingChanged也会被调用,但参数为true。该onCommit回调要求先前选择TextField

编辑2: 添加一个示例,用于committed()在用户点击return或change TextField时以及changed()在用户点击时是否要调用函数TextField

@State var text = ""
var body: some View {
    VStack {
        TextField($text, placeholder: nil, onEditingChanged: { (changed) in
           if changed {
               self.changed()
           } else {
               self.committed()
           }
        }) {
            self.committed()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @jsbeginnerNodeJS 现在检查答案。`onCommit` 在它们切换时不会在前一个 `TextField` 上调用,而是调用 `onEditingChanged`,其参数等于 `false`。 (3认同)