TextField("Name", text: $name)
我找到了这个方法
func focusable(_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void = { _ in }) -> some View
但它只适用于MacOS,我该如何在iOS上做类似的事情?
您可以使用文本字段中存在的初始化程序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")
}
})
}
}
希望这有所帮助。
Hope this helps.
=>希望这有所帮助。
在iOS 15中,我们可以使用@FocusState
检测变化:
@FocusState private var isFocused: Bool
...
var body: some View {
Form {
TextField("Name", text: $name)
.focused($isFocused)
.onChange(of: isFocused) { isFocused in
// ...
}
}
}
.onFocus
has already been deprecated in favor of @FocusState
- harrisg
.alert
会触发带有false
值的onEditingChanged
函数。 - Roman Mahotskyi