本文介绍了SwiftUI中的textFieldDidBeginEditing和textFieldDidEndEditing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能将方法textFieldDidBeginEditingtextFieldDidEndEditing与Apple的默认TextField结构一起使用.

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

推荐答案

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)
    }
}

仅当用户选择textField时才调用onEditingChanged中的代码,而只有在点击返回,完成等操作时才调用onCommit.

The code in onEditingChanged is only called when the user selects the textField, and onCommit is only called when return, done, etc. is tapped.

编辑:当用户从一个TextField更改为另一个TextField时,先前选择的TextFieldonEditingChanged被调用一次,其中changed(参数)等于,然后也会调用刚刚选择的TextFieldonEditingChanged,但参数等于true.对于先前选择的TextField,不会调用onCommit回调.

When the user changes from one TextField to another, the previously selected TextField's onEditingChanged is called once, with changed (the parameter) equaling false, and the just-selected TextField's onEditingChanged is also called, but with the parameter equaling true. The onCommit callback is not called for the previously selected TextField.

修改2:添加一个示例,说明您要在用户点击return或更改TextField时调用函数committed()以及在用户点击TextField时调用changed()的情况:

Edit 2:Adding an example for if you want to call a function committed() when a user taps return or changes TextField, and changed() when the user taps the 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()
        }
    }
}

这篇关于SwiftUI中的textFieldDidBeginEditing和textFieldDidEndEditing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:25