迭代视图网格 SwiftUI [英] Iterate a grid of views SwiftUI

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

问题描述

我想获取一个长度可变的数组并返回一个具有 3 列和可变行长度的视图网格.视图应该根据数组值更新它的内容.

I'd like to take an array of variable length and return a grid of views with 3 columns and variable row lengths. The view should update it's content based off of the array value.

以下代码将为每张卡片显示一个 CardPicView,在滚动视图中标题为A"...I".

The following code will present a CardPicView for each card, with the title of "A"... "I" in a scroll view.

struct ContentView : View {
    let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
    var body: some View {
        ScrollView {
            ForEach(cards.identified(by: \.self)) { card in
                    CardPicView(cardTitle: card)
            }
        }
    }
}

我想把这个滚动视图分成 3 列,本质上.

I would like to take this scrollview and divide it into 3 columns, essentially.

我发现下面的代码可以使用以下代码创建合适大小的网格:

I have figured out that the below code can create a grid of the right size by using:

struct ContentView : View {
    let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
    var body: some View {
        ScrollView{
            ForEach(0..<cards.count/3) { row in // create number of rows
                HStack {
                    ForEach(0..<3) { column in // create 3 columns
                        Text(self.cards[row])
                    }
                }
            }
        }
    }
}

然而,这给了我一个只有 (AAA/BBB/CCC/DDD) 的 3x4 网格

However, this gives me a 3x4 grid with just (AAA/BBB/CCC/DDD)

将其更改为:

struct ContentView : View {
    let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
    var body: some View {
        ScrollView{
            ForEach(0..<cards.count/3) { row in // create number of rows
                HStack {
                    ForEach(0..<3) { column in // create 3 columns
                        Text(self.cards[column])
                    }
                }
            }
        }
    }
}

给我一​​个只有 (ABC/ABC/ABC/ABC) 的 3x4 网格.

Gives me a 3x4 grid with just (ABC/ABC/ABC/ABC).

我不知何故需要使用两个索引遍历行和列,但不确定如何快速执行此操作.

I somehow need to iterate over row and column using two indices, but not sure how to do this in swift.

推荐答案

我认为 SwiftUI 中没有任何特定的东西可以防止这种情况发生.我认为这就是您要完成的任务?

I don't think there's anything specific in SwiftUI that prevents this. I think this is what you're trying to accomplish?

struct ContentView : View {
    let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
    var body: some View {
        ScrollView{
            ForEach(0..<cards.count/3) { row in // create number of rows
                HStack {
                    ForEach(0..<3) { column in // create 3 columns
                        Text(self.cards[row * 3 + column])
                    }
                }
            }
        }
    }
}

这篇关于迭代视图网格 SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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