【问题标题】:SwiftUI run function on losing focus TextFieldSwiftUI 在失去焦点时运行函数 TextField
【发布时间】:2021-09-03 22:03:15
【问题描述】:

每当文本字段失去焦点时,我想运行一些函数。 文本字段已经有 onEditingChange 和 onCommit 但我想在用户离开文本字段后运行验证功能。

onblur 为网络所做的相似,不会使屏幕上的任何其他视图混乱。

【问题讨论】:

  • onEditingChanged 有什么问题?当用户离开文本字段时,我会给你false

标签: events swiftui textfield


【解决方案1】:

在 iOS 15 中,@FocusState.focused 可以为您提供此功能。在 iOS 13 和 14 上,您可以使用onEditingChanged(显示在第二个TextField

struct ContentView: View {
    @State private var text = ""
    @State private var text2 = ""
    @FocusState private var isFocused: Bool

    var body: some View {
        TextField("Text goes here", text: $text)
            .focused($isFocused)
            .onChange(of: isFocused) { newValue in
                if !newValue {
                    print("Lost focus")
                }
            }
        TextField("Other text", text: $text2, onEditingChanged: { newValue in
            print("Other text:",newValue)
        })
            
    }
}

【讨论】:

  • 对于 13 或以下的 IO 是否有类似的东西?
  • 更新了我的答案——onEditingChanged 适用于 iOS 13 和 14
猜你喜欢
  • 2020-05-27
  • 2022-11-21
  • 2020-05-24
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多