[英]Fire some code when dismissing SwiftUI modal
I have a modal built with SwitftUI which has a TextField
with onCommit:
code which saves user input from @State
variable to file when user taps "return" on keyboard.我有一个用 SwitftUI 构建的模式,它有一个带有
onCommit:
的TextField
onCommit:
代码,当用户在键盘上点击“返回”时,该代码将用户输入从@State
变量保存到文件中。
However, if user types something inside TextField
and then dismisses the modal without pressing "return", the onCommit:
code doesn't fire and user input stays unsaved.但是,如果用户在
TextField
键入内容,然后在不按“返回”的情况下关闭模式,则onCommit:
代码不会触发并且用户输入保持未保存状态。 How do I fire some code accessing inner variable of my modal View when it is dismissed?当我的模态视图被解除时,如何触发一些访问内部变量的代码?
Try the following:请尝试以下操作:
Instead having a private @State var on your modal, make it an internal @Binding
that you pass into the modal from the call site.取而代之的是在你的模态上有一个私有的 @State 变量,让它成为你从调用站点传递到模态的内部
@Binding
。 This way the modified bound variable is available on both the caller and the modal view.这样修改后的绑定变量在调用者和模态视图上都可用。
import SwiftUI
struct ContentView: View {
@State var dismiss = false
@State var txt = ""
@State var store = ""
var body: some View {
VStack {
Text("modal").sheet(isPresented: $dismiss, onDismiss: {
self.store = self.txt
}) {
TextField("txt", text: self.$txt) {
self.store = self.txt
}.padding().border(Color.red)
}.onTapGesture {
self.dismiss.toggle()
}
Text(store)
}
}
}
struct ContetView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.