视图中的嵌套 ForEach(和列表)会产生意想不到的结果 [英] Nested ForEach (and List) in Views give unexpected results

查看:25
本文介绍了视图中的嵌套 ForEach(和列表)会产生意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SwiftUI 视图中的另一个 ForEach 中执行 ForEach 会产生意想不到的结果 - 几乎就像他们踩到彼此的计数器一样.不清楚发生了什么.我需要显示多分支数组并尝试了许多变体,但一直遇到同样的问题

Doing a ForEach within another ForEach in a SwiftUI View produces unexpected results - almost like they are stepping on each other's counters. Not clear as to what's happening. I need to display multi branched arrays and have tried a number of variants but keep running into the same problem

我有几个项目出现了这个问题.尝试使用范围 (0..

这只是测试版问题还是我遗漏了什么?我已经包含了一个演示问题的示例项目.

I have a few projects where this has come up. Tries using ranges (0..

Is this just a beta issue or am I missing something? I've included an example project that demonstrated the problem.

使用 XCode 11 Beta (11M392r)

using XCode 11 Beta (11M392r)

谢谢!

import SwiftUI

struct ContentView: View {

    let topTier:[String] = ["Apple", "Banana", "Cherry"]
    let nextTier:[String] = ["Abalone", "Brie", "Cheddar"]


    var body: some View {
        List {

            ForEach (topTier.indices, id: \.self) { a in

                Text(self.topTier[a])

                ForEach (self.nextTier.indices, id: \.self) { b in

                    Text(self.nextTier[b]).padding(.leading, 20)

                }

            }
        }
    }
}

在最合适的 ForEach 上抛出对成员‘索引’的不明确引用".

throws "Ambiguous reference to member 'indices'" on the fitst ForEach.

如果内部 ForEach 被注释,它会显示水果如果外部 ForEach 被注释,它可以显示奶酪

If the inner ForEach is commented it works displaying the fruits If the outter ForEach is commented it works displaying the cheeses

我希望它显示:苹果鲍鱼布里干酪切达干酪香蕉鲍鱼布里干酪切达干酪樱桃鲍鱼布里干酪切达干酪

I want it to display: Apple Abalone Brie Cheddar Banana Abalone Brie Cheddar Cherry Abalone Brie Cheddar

推荐答案

与在此期间使用 SwiftUI 的新 @ViewBuilder 语法产生的许多错误一样测试周期,模棱两可的参考……"消息是一个红鲱鱼.您的问题是 ForEach 闭包需要单个视图,而不是视图构建器.

As with many of the errors that come out of the new @ViewBuilder syntax with SwiftUI during this beta cycle, the "Ambiguous reference…" message is a red herring. Your issue is that the ForEach closure expects a single view, not a view builder.

您只需将 ForEach 闭包的主体包装在 Group 中即可使您的视图正常工作,如下所示:

You can get your view working by simply wrapping the body of the ForEach closure in a Group, like so:

import SwiftUI

struct ContentView: View {

    let topTier:[String] = ["Apple", "Banana", "Cherry"]
    let nextTier:[String] = ["Abalone", "Brie", "Cheddar"]


    var body: some View {
        List {

            ForEach (topTier.indices, id: \.self) { a in
                Group {
                    Text(self.topTier[a])

                    ForEach (self.nextTier.indices, id: \.self) { b in

                        Text(self.nextTier[b]).padding(.leading, 20)

                    }
                }
            }
        }
    }
}

瞧:

这篇关于视图中的嵌套 ForEach(和列表)会产生意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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