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

SOLVED - Day 24 challenge 3

Forums > 100 Days of SwiftUI

hello!

I am totally stumped on this challenge. I know we are being askwd to crwate a view that returns an image. Ive tried creating a View named FlagReturn that returns an Image but i cant get it to compile because the Image in the actual code we are copy/pasting from the ForEach loop returns the self.image of an array index that is inside its own scope. Im typing from my phone and cant upload my code but can anyone point me in the right direction or post what they used to solve?

Many Thanks!

3      

Well, through trial and error I finally figured it out. Anyone else struggling with it, here is how I solved it. Not sure it's the best way, but it works.

Create a View that returns an Image. I was getting tripped up by having the variable flag of type Image. As soon as I changed it to String it took the index and worked.

struct FlagView: View {
    var flag: String

    var body: some View {
        Image(flag)
            .renderingMode(.original)
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
            .shadow(color: .black, radius: 2)
    }
}

Then used the above FlagView View to replace the Image in the ForEach Loop.

                VStack (spacing: 30) {
                    ForEach(0..<3) { number in
                        Button(action: {
                            self.flagTapped(number)
                        }) {
                            FlagView(flag: self.countries[number])
                        }
                    }

Hope this helps somebody. Or if you knkow a better way to do it, please let me know. Thanks.

5      

Thanks so much for posting this. I wasn't grasping the setup of the FlagView struct... trying to pass the string right into the Image(string) instead of declaring that flag variable first. Thanks for posting this, definitely saved me.

3      

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.