问题描述
我偶然发现了 SwiftUI 中 Button
与自定义 ButtonStyle
相结合的奇怪行为.
I stumbled upon a weird behaviour for Button
s in SwiftUI in combination with a custom ButtonStyle
.
我的目标是创建一个带有某种推回动画"的自定义 ButtonStyle
.我为此使用了以下设置:
My target was to create a custom ButtonStyle
with some kind of 'push-back animation'. I used the following setup for this:
struct CustomButton<Content: View>: View {
private let content: () -> Content
init(content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack {
Button(action: { ... }) {
content()
}
.buttonStyle(PushBackButtonStyle(pushBackScale: 0.9))
}
}
}
private struct PushBackButtonStyle: ButtonStyle {
let pushBackScale: CGFloat
func makeBody(configuration: Self.Configuration) -> some View {
configuration
.label
.scaleEffect(configuration.isPressed ? pushBackScale : 1.0)
}
}
// Preview
struct Playground_Previews: PreviewProvider {
static var previews: some View {
CustomButton {
VStack(spacing: 10) {
HStack {
Text("Button Text").background(Color.orange)
}
Divider()
HStack {
Text("Detail Text").background(Color.orange)
}
}
}
.background(Color.red)
}
}
当我现在尝试在 Text
视图之外触摸这个按钮时,什么也不会发生.没有动画可见,也不会调用动作块.
When I now try to touch on this button outside of the Text
view, nothing will happen. No animation will be visible and the action block will not be called.
到目前为止我发现了什么:
What I found out so far:
- 当您删除
.buttonStyle(...)
时,它确实按预期工作(当然没有自定义动画) - 或者当您在
CustomButton
中的VStack
上设置.background(Color.red))
时,它也按预期工作与.buttonStyle(...)
的组合
- when you remove the
.buttonStyle(...)
it does work as expected (no custom animation of course) - or when you set a
.background(Color.red))
on theVStack
in theCustomButton
it does also work as expected in combination with the.buttonStyle(...)
现在的问题是,是否有人对如何正确解决此问题或如何解决此问题有更好的了解?
The question now is if anybody have a better idea of how to properly work around this issue or how to fix it?
推荐答案
只需在自定义按钮样式中添加点击测试内容形状,如下所示
Just add hit testing content shape in your custom button style, like below
使用 Xcode 11.4/iOS 13.4 测试
Tested with Xcode 11.4 / iOS 13.4
private struct PushBackButtonStyle: ButtonStyle {
let pushBackScale: CGFloat
func makeBody(configuration: Self.Configuration) -> some View {
configuration
.label
.contentShape(Rectangle()) // << fix !!
.scaleEffect(configuration.isPressed ? pushBackScale : 1.0)
}
}
这篇关于SwiftUI:自定义按钮无法识别具有清晰背景和 buttonStyle 的触摸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!