英文:
theres something like clearsOnBeginEditing for use in SwiftUI project?
问题
我需要在点击TextField时清除默认金额。
我已经为Storyboard项目找到了解决方案,但对于SwiftUI尚未找到。
英文:
I need to clear up TextField from default amount when i click to TextField
I have find solution for Storyboard project but not for SwiftUI
答案1
得分: 1
你可以使用 @FocusState
来实现这一点,并在 onChange(of:)
修饰符中清除字段。
以下是一个简单的示例,每当文本字段获得焦点时都会清除它:
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@FocusState private var field1InFocus: Bool
var body: some View {
VStack {
TextField("Field 1", text: $field1)
.focused($field1InFocus)
TextField("Field 2", text: $field2)
}
.onChange(of: field1InFocus) { inFocus in
if inFocus {
field1 = ""
}
}
}
}
英文:
You could use @FocusState
for this and clear the field in a onChange(of:)
modifier.
Here is a simple example that clears a text field every time it gets focus
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@FocusState private var field1InFocus: Bool
var body: some View {
VStack {
TextField("Field 1", text: $field1)
.focused($field1InFocus)
TextField("Field 2", text: $field2)
}
.onChange(of: field1InFocus) { inFocus in
if inFocus {
field1 = ""
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论