SwiftUI:清除模式状态或重新初始化 [英] SwiftUI: Clear Modal state or Reinitialize

查看:458
本文介绍了SwiftUI:清除模式状态或重新初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SwiftUI模式,我想清除状态或重新初始化.考虑到该模式可以打开可能具有某种状态的其他模式,因此最好重新启动.

I have a SwiftUI modal that I would like to either clear the state of or reinitialize. Reinitalizing would be preferred considering the fact that this modal can open other modals that may have some state.

这是一个简单的例子:

import SwiftUI

struct OtherView: View {
    @State var otherViewState: String = ""

    var body: some View {
        TextField($otherViewState, placeholder: Text("Demo Text Input"))
    }
}

struct Demo: View {
    @State var showModal: Bool = false

    var modal: Modal {
        Modal(OtherView(), onDismiss: { self.showModal = false })
    }

    var body: some View {
        Button(action: { self.showModal = true }) {
            Text("Toggle Modal")
        }
        .presentation(self.showModal ? self.modal : nil)
    }
}

不管如何关闭OtherView,我都希望在清除文本状态后重新打开它,并要求OtherView本身可以打开模式.在OtherView结构本身上添加clear方法始终是一种选择,但我认为它不是可维护的方法.

Regardless of how OtherView is dismissed, I would like to reopen it with its text state cleared, with the requirement that OtherView could open modals itself. Adding a clear method on the OtherView struct itself is always an option, but I don't find it to be a maintainable one.

以下是简化问题的视频:

Below is a video of the simplified problem:

推荐答案

9月11日更新:这似乎已在iOS 13 GM中修复.

Update September 11th: This appears to be fixed in iOS 13 GM.

我一直在努力解决同一问题,我想这是一个将在9月解决的错误,我已经将其提交到了反馈助手中,请确保做同样的事情!

I've been struggling with the same thing and I would like to think that this is a bug that will be resolve by September, I've already filed it on Feedback Assistant, make sure to do the same!

虽然现在您可以只创建一个新的UIHostingController,它包装要模态显示的SwiftUI视图.我知道它看起来确实很hacky,但至少可以正常工作:

For now though you can just create a new UIHostingController that wraps the SwiftUI View that you want to show modally. I know it looks really hacky but at least it works:

import SwiftUI

struct OtherView: View {
    @State var otherViewState: String = ""

    var body: some View {
        TextField($otherViewState, placeholder: Text("Demo Text Input"))
    }
}

struct Demo: View {
    var body: some View {
        Button("Toggle Modal") {
            self.showModal()
        }
    }

    func showModal() {
        let window = UIApplication.shared.windows.first
        window?.rootViewController?.present(UIHostingController(rootView: OtherView()), animated: true)
    }
}

您可能想改善窗口的获取方式,特别是如果您支持多个窗口,但我想您会想到的.

You might want to improve how you get the window, specially if you support multiple windows but I think you get the idea.

这篇关于SwiftUI:清除模式状态或重新初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆