问题描述
我怎样才能将方法textFieldDidBeginEditing
和textFieldDidEndEditing
与Apple的默认TextField结构一起使用.
how can I use the methods textFieldDidBeginEditing
and textFieldDidEndEditing
with the default TextField struct by apple.
推荐答案
TextField
具有onEditingChanged
和onCommit
回调.
例如:
@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
时,先前选择的TextField
的onEditingChanged
被调用一次,其中changed
(参数)等于,然后也会调用刚刚选择的TextField
的onEditingChanged
,但参数等于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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!