在第一个索引处向集合中插入新元素时,如何使用 PageTabViewStyle 修饰符更新 TabView 中的 SwiftUI 的 ForEach [英] How to update SwiftUI's ForEach in a TabView with PageTabViewStyle modifier when inserting a new element to the collection at first index

查看:24
本文介绍了在第一个索引处向集合中插入新元素时,如何使用 PageTabViewStyle 修饰符更新 TabView 中的 SwiftUI 的 ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在带有 TabView 中使用 ForEach 时,这是一个非常具体的问题PageTabViewStyle 修饰符.

This is a very specific issue when using ForEach in a TabView with PageTabViewStyle modifier.

每次我在数组的开头插入一个元素时,我的应用都会崩溃.

Every time I'm inserting an element at the beginning of my array my app crashes.

我收到了

尝试从更新前仅包含 11 个项目的第 0 部分中删除项目 11

错误.

在画布中它也会崩溃.

最后的常规附加工作正常,当我删除 PageTabViewStyle 修饰符时也能正常工作.

Regular appending at the end works fine, also when I remove the PageTabViewStyle modifier it works.

如果我需要详细说明或有任何问题,请告诉我.

Let me know if I need to elaborate more or if there are questions.

更新:我似乎在 iOS 15 中已修复此问题并且我的代码有效.我仍然希望找到适用于 iOS 14 的解决方法.

Update: I seems in iOS 15 this issue has been fixed and my code works. I'm still hoping to find a iOS 14 workaround.

我用一个简单的单页应用重现了这个问题:

I've reproduced the issue with a simple one page app:

import SwiftUI

struct SwiftUIView: View {

    @State var myArray: [String] = ["C", "D", "E", "F", "G"]

    var body: some View {

        VStack {
            Button("Insert before", action: {
                myArray.insert("A", at: 0)
            })
            TabView {
                ForEach(myArray, id: \.self) { value in
                    Text("\(value)")
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

推荐答案

这里是针对 Xcode 12.5/iOS 14.5 测试的解决方法.

Here is tested workaround for Xcode 12.5 / iOS 14.5.

TabView {
    ForEach(myArray, id: \.self) { value in
        Text("\(value)")
    }
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.id(myArray.count)      // << here !!

这篇关于在第一个索引处向集合中插入新元素时,如何使用 PageTabViewStyle 修饰符更新 TabView 中的 SwiftUI 的 ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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