SwiftUI ForEach 刷新使视图弹出 [英] SwiftUI ForEach refresh makes view pop

查看:31
本文介绍了SwiftUI ForEach 刷新使视图弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

<预><代码>导入 SwiftUI结构概述:查看{@ObservedObject var firstArray = FirstArray()var主体:一些视图{团体{滚动视图(){ForEach(self.firstArray.array, id: \.self){ 数组在子视图(数组:数组)}垫片()}}.navigationBarTitle("概览")}}结构子视图:查看{@State 变量数组var主体:一些视图{NavigationLink(目的地:DetailInfo(数组:数组){图像(系统名称:pencil.circle").可调整大小().框架(宽度:30,高度:30)}}.navigationBarTitle("子视图")}结构细节信息:查看{@State 变量数组var主体:一些视图{列表(){ForEach(0..<self.array.count, id: \.self){item in文本(项目)}.onDelete(执行:deleteItem)}}func deleteItem(at offsets: IndexSet) {self.array.remove(atOffsets: 偏移量)}}

当我删除 DetailInfo 中的一个项目时,它会弹出我回到 Overview.这是为什么?是不是因为 Overview 中的 ForEach刷新".我怎样才能留在 DetailInfo 上?当在 Overview 中省略 id: \.self 时,它不会显示这种行为.

解决方案

是的,这是因为一切都刷新了,所以详细视图和导航链接将不再存在,因此应用程序跳"回根视图

正常"解决方案是:不要删除详细信息视图中的项目,而是删除列表中的项目 - 这样就没有问题了,您也可以从 SwiftUI 中免费获得漂亮的动画

I have something like this:


import SwiftUI

struct Overview: View {

    @ObservedObject var firstArray = FirstArray()

    var body: some View {
        Group{
            ScrollView(){
                ForEach(self.firstArray.array, id: \.self){ array in
                    SubView(array: array)
                }
                Spacer()
            }
        }.navigationBarTitle("Overview")
    }
}


struct SubView: View {

    @State var array

    var body: some View {
           NavigationLink(destination: DetailInfo(array: array){
                Image(systemName: "pencil.circle").resizable().frame(width: 30, height: 30)
            }
    }.navigationBarTitle("SubView")
}


struct DetailInfo: View {

    @State var array

    var body: some View {
        List(){
            ForEach(0..<self. array.count, id: \.self){item in
                Text(item)
            }.onDelete(perform: deleteItem)
        }
    }

    func deleteItem(at offsets: IndexSet) {
       self.array.remove(atOffsets: offsets)
    }

}

When I delete an item in the DetailInfo it pops me back to the Overview. Why is that? Is that because of the ForEach "refreshing" in the Overview. How can I stay on the DetailInfo ? When leaving out the id: \.self in Overview it doesn't show this behaviour.

解决方案

yes, it is because everything gets refresh and so the detail view and the navigationlink won't exist anymore and so the app "jumps" back to the root view

the "normal" solution is: do not delete the item in the detail view but in the list - then there is no problem and you got a nice animation for free from SwiftUI too

这篇关于SwiftUI ForEach 刷新使视图弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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