0

I am trying to create a grid within SwiftUI where the index "snakes" from left-to-right, right-to-left, and left-to-right (ad infinitum). The approach that I've been trying to implement is essentially applying rotationEffect to each row, but the LazyVGrid's GridItems cannot handle a rotation effect.

An example of how I am looking to lay out the array

Providing some rough code for my View, but I am having trouble figuring out if there is a way of extending GridItem or applying a row-based rotationEffect without implementing a bunch of separate ForEach statements that rely on index checks (which seems inefficient, especially as I am using a single array and would need to drag and drop between them.

struct ContentView: View {
    
    @StateObject private var game = GameDriver()
    
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]
    
    var body: some View {
        
        LazyVGrid(columns: columns, spacing: 8) {

            ForEach(Array(game.hand.enumerated()), id: \.offset) { index, tile in
                 CardView(game: self.game, card: card)
                }
            }
        }
 

I have tried to implement a rotationEffect on GridItem, but Type Grid Item does not have rotationEffect as a member, so I cannot affect the whole row. I have also tried implementing the rotationEffect within ForEach, but as expected, that only results in an individual card being flipped upside down, as opposed to the whole row as desired.

  • Do some math to identify which items are flipped. Every other group of 4. – cora Dec 30 '22 at 00:28
  • @cora - Definitely. That math isn't particularly hard. The difficult part seems to be applying the rotation transformation to a group of items/the row as opposed to each individual item (what I'm looking to do is Row 1: 1 2 3 4 | Row 2: 8 7 6 5 (All Flipped Together). I have been able to get 1 2 3 4 | 5 6 7 8 (Each individual item is flipped) by applying the rotationEffect on the ForEach part of the code. – DannyDevitoPhD Dec 30 '22 at 01:57
  • What I would do is break up the main array in groups of 4. Odd elements are normal, even are .reversed and with rotation. You could combine the two arrays of you think it is more manageable. – cora Dec 30 '22 at 02:03

0 Answers0