Clone Help

Hey everyone. So I've been making an app where you can click a button and add an image to the app. But, since I'm new, I can't figure out how to have a button whose action is adding an image. My idea would be:

Button("Bush") { Image("Bush") }

but that doesn't work. Please help!

Accepted Answer

I guess it is SwiftUI ?

If so, you need to do it through a State var, not call directly a View in a button action.

Declare

@State private var showImage = false

Then in body:

Button("Bush") { showImage = true }

if showImage { Image("Bush") }

If you want show/hide:

Button("Bush") { showImage .toggle() }

Thanks for the response. I think I meant something a bit different - I was probably unclear. First of all, yes, it is SwiftUI. But I meant more of a cloning process. Your process works, but what if I want the user to be able to add more than one bush? I'm trying to figure out a way to have an image hidden, but when the button is pressed it makes a new clone of the image, and have that clone show itself. Can you help me with that? I've done tons of research on how to clone, but I can't figure it out.

If you need more clarity, here is an outline of the function:

  1. User pushes "Bush" Button
  2. A Bush appears on the screen.
  3. The user can press the button again to create another bush.

Thanks. Sorry if I'm being inconvenient.

You have several ways to do it.

One is to count images

Declare a State var to count images

@State private var imagesCount = 0

Change the button action to increment count

Button("Bush") { imagesCount += 1 }

Then show as many images as needed, for instance in a HStack

HStack {
 ForEach (0..<imagesCount, id: \.self) { _ in 
    Image("Bush")
  }
}

You could use an index to have a different image each time

HStack {
 ForEach (0..<imagesCount, id: \.self) { index in 
    Image("Bush") // change "Bush" by something depending on the index
  }
}

It gave me some weird warning about not being able to declare private variables. I probably misplaced something.

Yes it is misplaced.

State var declaration must be BEFORE the var body, not inside.

.

The script only changes if the button hides or not, it doesn't duplicate anything..

I tested, it does work properly.

Can you explain and show more code ?

Clone Help
 
 
Q