Scenario:
In SwiftUI
, my TextField
has a Double
value. On tapping/focusing the TextField
the current Double
value is cleared, to allow the user to easily enter a new value without having to select and delete the current value. If the user does not enter a new value, the old value is restored on deselect.
发行
利用.focused()
和.onChange(of:)
似乎不可能做到这一点.下面的代码正确清除了该值(在控制台中可见).但是,更改不会反映在用户界面中.通过在TextField
上使用.id()
来强制更新UI会取消 Select TextField
,从而使此解决方法毫无用处.
为什么用户界面没有从更改更新为TextField
值属性?
struct ContentView: View {
@FocusState var focus: Bool
@State var test: Double? = 100
@State var id: UUID = UUID()
var body: some View {
VStack {
TextField("Placeholder", value: $test, format: .number)
.id(id)
.focused($focus)
.onChange(of: focus, perform: { editing in
var oldValue: Double? = test
if editing {
self.$test.wrappedValue = nil
self.$id.wrappedValue = UUID()
} else {
if test == nil {
self.$test.wrappedValue = oldValue
self.$id.wrappedValue = UUID()
}
}
})
}
.padding()
}
}
有没有办法用SwiftUI
的TextField
来做到这一点?