[英]SwiftUI - How to change the button's image on click?
我正在尝试这样做,以便当我单击一个按钮(这是其他按钮列表的一部分)时,单击的按钮的图像从“star”变为“star.fill”。 请帮忙!
ForEach(pies, id: \.self) { pie in
Button(action: {
// some action
}) {
HStack {
Image(systemName: "star")
Text(pie)
Spacer()
}
}
我有一个播放/暂停按钮。
按钮图像会根据它是否正在播放而变化。
在我看来,我有一个变量:
@State var isPlaying : Bool = false
然后,每当您单击该按钮时, isPlaying
都会发生变化 -> 如果它为 true,则变为 false,反之亦然。 按钮图像由ternary operator
设置。
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: self.isPlaying == true ? "pause.fill" : "play.fill")
.resizable()
.frame(width: 60, height: 60)
}
您可以使用@State
变量来存储图像名称并在单击按钮时更改它:
@State var imageName: String = "star"
ForEach(pies, id: \.self) { pie in
Button(action: {
self.imageName = "star.fill"
}) {
HStack {
Image(systemName: imageName)
Text(pie)
Spacer()
}
}
您可以使用自定义按钮样式根据按下的 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))
}
}
为了便于使用,您可以创建一个使用按钮样式的视图:
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)
}
}
然后像这样使用它:
ImageButton(
image: "your_unpressed_image",
pressedImage: "your_pressed_image",
action: { ... }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.