1

Given a list of numbers which is required to display as a list of rows of 7 elements (consider days in calendar iOS app), is it possible to conditionally wrap HStack in VStack if a number divides by modulo, for example?

    VStack(alignment: .center, spacing: 10) {
        ForEach(1...self.getDays(), id: \.self) { day in
            // something like if (day % 7 == 0) { VStack
            HStack(alignment: .center, spacing: 10) {
                DayView(dayNumber: day)
            }
        }
    }

Or, perhaps it is possible to apply the group by every 7 elements in the list, without ViewBuilder?

Ilja
  • 1,205
  • 1
  • 16
  • 33

2 Answers2

2
struct Person {
     let id: Int
     let name: String
}
var EgArray:[Person] = [
    Person(id: 1, name: "Jonh"),
    Person(id: 2, name: "Lee"),
    Person(id: 3, name: "George"),
    Person(id: 4, name: "Jonh"),
    Person(id: 4, name: "Jonh")
]
let result = Dictionary(grouping: EgArray) { $0.name }
Bunthoeun
  • 143
  • 1
  • 1
  • 11
0

You should create a data structure that represents the structure of your view first: try transforming 1...self.getDays() into a 2D array, with each inner array being one row of your "grid". For example, if self.getDays were 10, the 2D array would look like:

[
    [1,2,3,4,5,6,7],
    [8,9,10]
]

After that, we can use two ForEaches to "loop through" (We aren't actually looping through anything. ForEach is not really a loop...) the 2D array and create the view.

To create the 2D array, you can use one of the ways from this answer.

And then you can do:

VStack(alignment: .center, spacing: 10) {
    // "chunked" does the aforementioned transformation
    ForEach(Array(1...self.getDays()).chunked(by: 7), id: \.self) { row in
        HStack(alignment: .center, spacing: 10) {
            ForEach(row, id: \.self) { day in
                DayView(dayNumber: day)
            }
        }
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313