【问题标题】:Expand SwiftUI button tap area over the button frame在按钮框架上展开 SwiftUI 按钮点击区域
【发布时间】:2020-09-06 17:45:38
【问题描述】:

我阅读了关于该问题的类似question。但这只会扩大按钮大小使用.padding()。快照中的红色区域是可点击区域。

SwiftUI.framework 插入的屏幕边缘的尾随填充无法删除(我认为)。这导致屏幕右边缘的任何点击都无法触发按钮动作。如何使可点击区域超出按钮大小?这样用户就可以更轻松地点击该按钮。

谢谢。

.navigationBarItems(trailing:
    Button(action: {
        self.context.isSheetDisplay = true
    }, label: {
        Image(systemName: "square.and.pencil")
            .font(.system(size: 20))
    })
    .padding([.leading, .top, .bottom])
    .background(Color.red)
)

更新:

例如 模拟器中的 Photos.app 可以在边缘触发点击。

【问题讨论】:

  • 这是一个已知的 SwiftUI 错误,所有建议都只是解决方法。如果你想要 UIKit 行为,那么现在就使用 UIKit。
  • .contentShape(_:) 表示:定义命中测试的内容形状。我尝试使用该修饰符来扩大命中测试区域。但不是成功。我们真的需要更多的文档和代码示例。 :)

标签: ios swift user-interface swiftui navigationbar


【解决方案1】:

我对 iOS 的这个问题的解决方案是为按钮添加一个几乎透明的背景颜色 ViewModifier 作为 ButtonStyle 的一部分:

import SwiftUI

struct ExampleBigPaddedButton: View {
    var body: some View {
        Button("Tap anywhere inside") {
            print("Tapped")
        }.buttonStyle(BigPaddedButtonStyle())
    }
}

struct BigPaddedButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        return configuration
            .label
            .foregroundColor(configuration.isPressed ? .gray : .black)
            .padding(EdgeInsets(top: 75, leading: 25, bottom: 75, trailing: 25))
            .background(Color(red: 1, green: 1, blue: 1, opacity: 0.01))
            .background(Rectangle().stroke(Color.gray))
    }
}

struct ExampleBigPaddedButton_Previews: PreviewProvider {
    static var previews: some View {
        ExampleBigPaddedButton()
    }
}

这将生成一个按钮,该按钮具有您需要的任何大小的填充,可以在其范围内的任何位置点击。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多