在以下情况下如何隐藏keyboard使用SwiftUI?
情况1
我有TextField,我需要keyboard在用户单击return按钮时隐藏。
情况二
我有TextField,keyboard当用户在外面轻按时,我需要隐藏。
我该如何使用SwiftUI呢?
注意:
我尚未提出有关的问题UITextField。我想使用SwifUI(TextField)来做。
I'm trying to get a numeric field updated so I'm using a TextField with the formatter: parameter set. It formats the number into the entry field just fine, but does not update the bound value when edited. The TextField works fine (on Strings) without the formatter specified. Is this a bug or am I missing something?
UPDATE: As of Xcode 11 beta 3 it kind of works. Now if you edit the numeric TextField, the bound value is updated after …
我有一个简单的TextField可以像这样绑定到状态“位置”,
TextField("Search Location", text: $location)
Run Code Online (Sandbox Code Playgroud)
我想在每次该字段更改时调用一个函数,如下所示:
TextField("Search Location", text: $location) {
self.autocomplete(location)
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用。我知道有一些回调,onEditingChanged-但是,仅当该字段聚焦时,才似乎触发该回调。
如何在每次更新字段时调用此函数?
我有一个 ObservableObject 应该保存我的应用程序状态:
final class Store: ObservableObject {
@Published var fetchInterval = 30
}
Run Code Online (Sandbox Code Playgroud)
现在,该对象被注入到我的层次结构的根部,然后在树下的某个组件中,我尝试访问它并将其绑定到 TextField,即:
struct ConfigurationView: View {
@EnvironmnetObject var store: Store
var body: some View {
TextField("Fetch interval", $store.fetchInterval, formatter: NumberFormatter())
Text("\(store.fetchInterval)"
}
}
Run Code Online (Sandbox Code Playgroud)
$),属性也不会被更新,初始值会正确显示,但是当我更改它时,文本字段会发生变化,但绑定不会传播$fetchInterval
.debounce(for: 0.8, scheduler: RunLoop.main)
.removeDuplicates()
.sink { interval in
print("sink from my code \(interval)")
}
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢。
编辑:我刚刚发现对于文本变量,绑定开箱即用,效果很好,例如:
// on store
@Published var testString = "ropo"
// on component
TextField("Ropo", text: $store.testString)
Text("\(store.testString)")
Run Code Online (Sandbox Code Playgroud)
仅在 int 字段上它没有正确更新变量
编辑2:好的,我刚刚发现仅更改字段是不够的,必须按下Enter才能传播更改,这不是我想要的,我希望每次更改字段时都会传播更改......