在SwiftUI项目中是否有类似clearsOnBeginEditing的功能?

huangapple go评论65阅读模式
英文:

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 = ""
            }
        }
    }
}

huangapple
  • 本文由 发表于 2023年2月26日 21:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定