UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 35 Edutainment Question: Stacking images 2 x 2

Forums > 100 Days of SwiftUI

I have been making some solid progress and am close to wrapping this Challenge up. The main thing I am strugging with is how to set up the 4 multi-choice images in a 2 x 2 grid. See screenshot and code:

https://i.ibb.co/XpNJBTR/Screen-Shot-2020-06-27-at-8-21-43-PM.png

https://i.ibb.co/XpNJBTR/Screen-Shot-2020-06-27-at-8-21-43-PM.png

Here is my code. FYI, it is inside a VStack.

https://i.ibb.co/86Z7mfV/Screen-Shot-2020-06-27-at-8-23-07-PM.png

https://i.ibb.co/86Z7mfV/Screen-Shot-2020-06-27-at-8-23-07-PM.png

Can anyone someone point me in the right direction on how to accomplish this?

2      

You might want to read How to position views in a grid using LazyVGrid and LazyHGrid so depending on which version of Xcode, but if earlier then you add a new struct (I would put in a new file)

struct GridStack<Content: View>: View {
    let rows: Int
    let columns: Int
    let content: (Int, Int) -> Content

    var body: some View {
        VStack {
            ForEach(0 ..< rows, id: \.self) { row in
                HStack {
                    ForEach(0 ..< self.columns, id: \.self) { column in
                        self.content(row, column)
                    }
                }
            }
        }
    }

    init(rows: Int, columns: Int, @ViewBuilder content: @escaping (Int, Int) -> Content) {
        self.rows = rows
        self.columns = columns
        self.content = content
    }
}

Then replace your HStack with

GridStack(rows: 2, columns: 2) { row, col in
    Button(action: {
      self.checkAnswer(row * 2 + col)
    }) {
      AnimalImage(image: self.animalImageNames[row * 2 + col])
        .scaledToFit()
        .padding()

      Text("\(self.answerArray[row * 2 + col].answer)")
        .font(.largeTitle)
    }
    .padding()
}

PS please put code using </> is make it eassy to read and copy so I have made some typo in above with your code but you should get the idea

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.