16
TextField("Name", text: $name)

我找到了这个方法

func focusable(_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void = { _ in }) -> some View

但它仅适用于 MacOS,我该如何为 iOS 做类似的事情?

4

2 回答 2

28

您可以使用init(_:text:onEditingChanged:onCommit:)文本字段中存在的初始化程序。当您开始编辑和结束编辑时,您将触发一个动作。您可以在下面找到最小的示例。

import SwiftUI

struct ContentView: View {
    @State private var greeting: String = "Hello world!"
    var body: some View {
        TextField("Welcome", text: $greeting, onEditingChanged: { (editingChanged) in
            if editingChanged {
                print("TextField focused")
            } else {
                print("TextField focus removed")
            }
        })
    }
}

希望这可以帮助。

于 2019-10-16T05:40:57.073 回答
14

iOS 15

在 iOS 15 中,我们可以通过以下方式检测更改@FocusState

@FocusState private var isFocused: Bool
...

var body: some View {
    Form {
        TextField("Name", text: $name)
            .focused($isFocused)
            .onChange(of: isFocused) { isFocused in
                // ...
            }
    }
}
于 2021-06-08T20:06:12.177 回答