[英]Make a multilines Component() with ForEach loop ? [SwiftUI]
I have a loop that display all of my MyView() elements :我有一个循环显示我的所有 MyView() 元素:
HStack() {
ForEach(datastore.datacard) { data in
MyView()
}
}
But I want to have a maximum of 4 item MyView() per line on my screen I have a list of 10 elements and I don't want to use a ScrollView).但是我希望屏幕上每行最多有 4 个项目 MyView() 我有一个包含 10 个元素的列表,我不想使用 ScrollView)。 I don't know, like trigger an Hstack() at each 4 elements ?
我不知道,比如每 4 个元素触发一个 Hstack() ?
Is it possible ?是否可以 ?
Thank you谢谢
There is a initializer for ForEach taking a Range: https://developer.apple.com/documentation/swiftui/foreach/3364099-init ForEach 有一个范围的初始化程序: https : //developer.apple.com/documentation/swiftui/foreach/3364099-init
ForEach(0..<4) { index in
MyView()
}
if you need to access the data provided in datastore.datacard
inside your ForEach you could access the data via the index:如果您需要访问 ForEach 中
datastore.datacard
提供的datastore.datacard
,您可以通过索引访问数据:
ForEach(0..<(datastore.datacard.count < 4 ? datastore.datacard.count : 4)) { index in
MyView(self.datastore.datacard[index])
}
First, you need to split data array into chunks using this extension:首先,您需要使用此扩展将数据数组拆分为块:
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
then you can set the array size:然后你可以设置数组大小:
let chunksResult = datastore.datacard.chunked(into: 4)
For the UI Try this对于 UI 试试这个
VStack {
ForEach(chunksResult) { rowData in
HStack {
ForEach(rowData) { columnData in
MyView()
}
}
}
}
this is the sample code and needs to be test in Xcode, I just write the code to have a clue on how you can manage it这是示例代码,需要在 Xcode 中进行测试,我只是编写代码以了解如何管理它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.