更改可点击按钮区域的大小–contentShape(_:)不起作用



我正在SwiftUI中使用TabView(selection:)制作一个自定义选项卡栏,并将默认选项卡隐藏在ContentViewinit中(我知道这不是一个好做法(。

我在选项卡视图中有两个选项卡按钮,如下所示:

HStack(spacing: 0) {
Button(action: { selectedTab = .history  }) {
EmptyView()
}
.buttonStyle(TabButtonStyle(systemImage: "rectangle.stack.person.crop", tab: .history, currentTab: selectedTab))

Spacer()

Button(action: { selectedTab = .profile }) {
EmptyView()
}
.buttonStyle(TabButtonStyle(systemImage: "person.crop.circle", tab: .profile, currentTab: selectedTab))
}
.overlay(tapButton)
.padding(.horizontal, 50)
.padding(.vertical, 10)
.padding(.bottom, UIApplication.shared.windows.first?.safeAreaInsets.bottom)
.ignoresSafeArea(.all, edges: .bottom)

tapButton是一个覆盖在顶部的自定义选项卡按钮,填充用于重新创建默认选项卡栏的尺寸。

对于TabButtonStyle(对于自定义行为来说是必要的,在用户按下图像时,而不是在他们松开手指后,图像切换到填充的替代图像(,如下所示:

struct TabButtonStyle: ButtonStyle {
let systemImage: String
let tab: Tab
var currentTab: Tab

func makeBody(configuration: Configuration) -> some View {
return Image(systemName: configuration.isPressed || tab == currentTab ? "(systemImage).fill" : systemImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 25, height: 25)
}
}

虽然这很有魅力,但可敲击区域最终只是图像,对我们的手指来说太小太挑剔了。改变这一点的常用方法是添加contentShape(_:)修饰符——然而,当我添加它时(无论是添加到TabButtonStyle还是添加到按钮本身之后(,按钮就不能再点击了。无论我在争论中给出的形状如何,它都不会对敲击做出响应。

是不是我做错了什么,可能是因为EmptyView?即使没有contentShape(_:),它也能正常工作吗?也许这是由于contentShape(_:)的内部工作。

添加填充适用于Xcode 12.1/iOS 14.1

return Image(systemName: configuration.isPressed || tab == currentTab ? "(systemImage).fill" : systemImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 25, height: 25)
.padding()                      // << here !!

最新更新