简体   繁体   中英

SwiftUI - How to change the button's image on click?

I'm trying to make it so that when I click a button (that is part of a list of other buttons), the image for the clicked button changes from "star" to "star.fill". Please help!

ForEach(pies, id: \.self) { pie in
      Button(action: {
          // some action
       }) {
       HStack {
           Image(systemName: "star")
           Text(pie)
           Spacer()
       }
}

I have a play/pause button.
The button image changes depending on if it is playing or not.

In my View I have a variable:

@State var isPlaying : Bool = false

Then, whenever you click the button, isPlaying is changing -> if it was true it becomes false and vice versa. The button image is set by ternary operator .

Button(action: {
   self.isPlaying.toggle()
}) {
    Image(systemName: self.isPlaying == true ? "pause.fill" : "play.fill")
          .resizable()
          .frame(width: 60, height: 60)
}

You can use a @State variable to store the image name and change it on button click:

@State var imageName: String = "star"

ForEach(pies, id: \.self) { pie in
      Button(action: {
          self.imageName = "star.fill"
       }) {
       HStack {
           Image(systemName: imageName)
           Text(pie)
           Spacer()
       }
}

You can use a custom button style to determine which image is displayed based on the pressed state:

struct ImageButtonStyle: ButtonStyle { 
    var image: String
    var pressedImage: String

    func makeBody(configuration: Self.Configuration) -> some View {
      let displayImage = configuration.isPressed ? pressedImage : image
      return Image(displayImage, bundle: Bundle(for: SomeClassInYourApp.self))
    }
}

For ease of use, you can create a view which uses the button style:

struct ImageButton: View {
    
    var image: String
    var pressedImage: String
    var action: () -> Void
    
    var body: some View {
        Button(action: self.action) { }
            .buttonStyle(ImageButtonStyle(image: image, pressedImage: pressedImage)
    }
}

Then use it like this:

ImageButton(
    image: "your_unpressed_image", 
    pressedImage: "your_pressed_image", 
    action: { ... }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM