SwiftUI: Clear Modal state or Reinitialize(SwiftUI:清除模态状态或重新初始化)

本文介绍了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 视图.我知道它看起来很老套,但至少它有效:

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:清除模态状态或重新初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!