简体   繁体   English

SwiftUI 单击按钮后弹出视图

[英]SwiftUI view popping back after button click

This is a question that I already have the answer to, but I just thought I'd share it here in case someone gets absolutely mad too over something similar.这是一个我已经有了答案的问题,但我只是想我会在这里分享它,以防有人对类似的事情感到非常生气。

I realised that my detail view was popping back whenever user interacted with it, by tapping somewhere and I couldn't figure it out why.我意识到每当用户通过点击某个地方与之交互时,我的详细视图就会弹出,我无法弄清楚为什么。

The detail view had 2 alerts, one single action and one double action.详细视图有 2 个警报,一个单一操作和一个双重操作。 Since in SwiftUI you can't have 2 sequential alerts applied to the same view I usually add a Spacer() in between in order to make both of them appear.由于在 SwiftUI 中,您不能将 2 个连续警报应用于同一视图,因此我通常在两者之间添加一个 Spacer() 以使它们都出现。

Pls check answer with fix.请检查修复的答案。

This is the code with the 2 alerts I had in that view这是我在该视图中收到的 2 个警报的代码

.alert(isPresented: $alertCoordinator.isShowingDoubleAction) {
            Alert(
                title: Text(alertCoordinator.title),
                message: Text(alertCoordinator.message),
                primaryButton: .cancel(),
                secondaryButton: .destructive(
                    alertCoordinator.secondaryTitle,
                    action: { alertCoordinator.secondaryAction?() }
                )
            )
        }
        
        Spacer()
        .alert(isPresented: $alertCoordinator.isShowingSingleAction) {
            Alert(
                title: Text(alertCoordinator.title),
                message: Text(alertCoordinator.message),
                dismissButton: .default(
                    alertCoordinator.primaryTitle,
                    action: { alertCoordinator.primaryAction?() }
                )
            )
        }

For some weird reason adding the spacer in there was causing the view to pop back and as soon as I replaced it with an EmptyView() it all worked well and the issue went away.出于某种奇怪的原因,在其中添加垫片会导致视图弹回,一旦我用 EmptyView() 替换它,它就一切正常,问题就消失了。

If you know why this happens I'd love to know!如果你知道为什么会这样,我很想知道! Hope this helps someone facing this issue希望这可以帮助面临这个问题的人

In the case that this is deep in a NavigationView, could you try adding this line to your NavigationView:如果这是 NavigationView 的深处,您可以尝试将此行添加到 NavigationView 中吗:

.navigationViewStyle(.stack)

Otherwise these links might be able to help you:否则这些链接可能会帮助你:
SwiftUI sheet automatically dismisses itself SwiftUI 工作表自动关闭
SwiftUI NavigationView pops back when updating ObservableObject SwiftUI NavigationView 在更新 ObservableObject 时弹出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM