前情提要

在学习Swift Ui动画时,发现当我想要设置一个可变大按钮时,只能点击Button按钮的文字才会执行Button代码,而点击按钮的非文字区域就不会调取Button代码,具体的代码如下。
struct ContentView: View {
@State private var animationAmount = 1.0
var body: some View {
HStack {
Button("Tap Me") {
animationAmount += 0.5
}
.frame(width: 100, height: 100)
.background(.red)
.foregroundStyle(.white)
.clipShape(.circle)
.scaleEffect(animationAmount)
.animation(.easeIn, value: animationAmount)
}
}
}
经过排查发现是因为frame在按钮的外部设置,SwiftUI中,按钮的点击区域只有“Tap Me”的标签内容,因此只能通过点击文本部分触发Button代码。
解决方案
将设置Button的大小改为设置Button标签的大小,这样就可以完成点击按钮并执行Button代码。
struct ContentView: View {
@State private var animationAmount = 1.0
var body: some View {
HStack {
Button {
animationAmount += 0.5
} label: {
Text("Tap Me")
.frame(width: 100, height: 100)
}
.background(.red)
.foregroundStyle(.white)
.clipShape(.circle)
.scaleEffect(animationAmount)
.animation(.easeIn, value: animationAmount)
}
}
}