Home > OS >  Image disappearing after adding \(var) in Image
Image disappearing after adding \(var) in Image

Time:01-11

I am a beginner to Swift, SwiftUI, and using Xcode. I have been doing a couple of online tutorials and came across a problem when doing this bonus challenge.

import SwiftUI

struct ContentView: View {
    
    @State var userCredits = 1000
    @State var slot1 = 1
    @State var slot2 = 1
    @State var slot3 = 1
    
    var body: some View {
        VStack {
            Text("SwiftUI Slot!")
                .font(.system(size: 38))
                .fontWeight(.medium)
            Spacer()
            Text("Credits: \(userCredits)")
            Spacer()
            
            HStack{
                Image("apple\(slot1)")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                
                Image("cherry\(slot2)")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                
                Image("star\(slot3)")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
            Spacer()
            Button("Spin") {
                slot1 = Int.random(in: 1...3)
                slot2 = Int.random(in: 1...3)
                slot3 = Int.random(in: 1...3)
                
                if slot1 == slot2 && slot2 == slot3{
                    userCredits  = 15
                }
                else {
                    userCredits -= 5
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The images of the apple, cherry, and star disappear when I put the (slot#) after it

I tried taking out the (slot#) but that will simply display the picture of the images and not change them nor make the game work as intended

CodePudding user response:

You could do this by declaring an array of image names:

let imageNames = ["apple", "cherry", "star"]

then use something like:

HStack{
    Image(imageNames[slot1])
        .resizable()
        .aspectRatio(contentMode: .fit)
    
    Image(imageNames[slot2])
        .resizable()
        .aspectRatio(contentMode: .fit)
    
    Image(imageNames[slot3])
        .resizable()
        .aspectRatio(contentMode: .fit)
}

Also, don't forget that Swift arrays are zero based, so your spin function should be:

slot1 = Int.random(in: 0..<3)
slot2 = Int.random(in: 0..<3)
slot3 = Int.random(in: 0..<3)

CodePudding user response:

What you need is to add your images into an array and then use the values for your slot# properties as indices for getting an image from the array

So add an array property first to your view

let images = ["apple", "cherry", "star"]

Then change the call to Image(...) to use this array

Image(images[slot1 - 1])

and so on for the other two

  • Related