【问题标题】:SwiftUI Button cannot be clicked on its whole areaSwiftUI 按钮无法在其整个区域上单击
【发布时间】:2021-12-27 17:10:08
【问题描述】:

我构建了一个自定义按钮。
我的问题是,它只能在文本元素上单击,而不能在按钮的整个区域上单击。
怎么回事,怎么解决?

struct MyButton: View {
  
  var body: some View
  { Button( action:{ print("pressed") })
  { HStack {
      VStack(alignment: .leading){
        Text("Tomorrow").font(.caption)
        Text("23.5.22 KW 23")
      }
      Spacer()
    }
  }
  .padding([.horizontal],4.0)
  .padding([.vertical],2.0)
  .background(RoundedRectangle(cornerRadius: 5).fill(Color.red))
  .buttonStyle(PlainButtonStyle())
  .padding([.horizontal],8.0)
  }
}

【问题讨论】:

  • 将填充移动到 HStack,而不是按钮。

标签: swift swiftui


【解决方案1】:

默认情况下,只有实际渲染某些东西的视图部分是可点击的。您需要为您的Button 添加一个.contentShape(Rectangle()) 修饰符以使整个区域具有交互性。

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多