swift 如何将按钮的点击区域限制为内部的形状和标签?

pdkcd3nj  于 2024-01-05  发布在  Swift
关注(0)|答案(1)|浏览(163)

我在VStack中有两个导航按钮,我需要帮助将点击区域限制在形状上。目前,我可以在白色空间中稍微点击形状外部,而光标根本没有接触到形状。

  1. import SwiftUI
  2. struct ContentView: View {
  3. @State var showSecondView: Bool = false
  4. @State var showThirdView: Bool = false
  5. var body: some View {
  6. ZStack {
  7. // PLAY BUTTON
  8. VStack(spacing: 20) {
  9. NavigationStack {
  10. Button() {
  11. showSecondView.toggle()
  12. }
  13. label: {
  14. Text("Play")
  15. .font(.custom("Helvetica Neue", size: 25))
  16. .bold()
  17. .buttonBorderShape(.capsule)
  18. .padding(.horizontal, 40)
  19. .padding(.vertical, 10)
  20. .background(.pink)
  21. .foregroundColor(.white)
  22. .cornerRadius(25)
  23. }
  24. .navigationDestination(
  25. isPresented: $showSecondView) {
  26. SecondView()
  27. }
  28. Spacer().frame(height: 25) //space between buttons
  29. // HOW TO PLAY BUTTON
  30. Button() {
  31. showThirdView.toggle()
  32. }
  33. label: {
  34. Text("How To Play")
  35. .font(.custom("Helvetica Neue", size: 25))
  36. .bold()
  37. .buttonBorderShape(.capsule)
  38. .padding(.horizontal, 20)
  39. .padding(.vertical, 10)
  40. .foregroundColor(.white)
  41. .background(.pink)
  42. .cornerRadius(25)
  43. }
  44. .navigationDestination(
  45. isPresented: $showThirdView) {
  46. ThirdView()
  47. }
  48. }
  49. }
  50. }
  51. }
  52. }

字符串
我不知道我需要添加或删除什么来解决这个问题。

jm2pwxwz

jm2pwxwz1#

您可以使用.contentShape(Rectangle())将点击区域限制为按钮的形状

  1. struct ContentView: View {
  2. @State var showSecondView: Bool = false
  3. @State var showThirdView: Bool = false
  4. var body: some View {
  5. ZStack {
  6. VStack(spacing: 20) {
  7. NavigationStack {
  8. Button(action: {
  9. showSecondView.toggle()
  10. }) {
  11. Text("Play")
  12. .font(.custom("Helvetica Neue", size: 25))
  13. .bold()
  14. }
  15. .buttonBorderShape(.capsule)
  16. .padding(.horizontal, 40)
  17. .padding(.vertical, 10)
  18. .background(.pink)
  19. .foregroundColor(.white)
  20. .cornerRadius(25)
  21. .contentShape(Rectangle()) // Restrict tap area
  22. .navigationDestination(isPresented: $showSecondView) {
  23. SecondView()
  24. }
  25. Spacer().frame(height: 25)
  26. Button(action: {
  27. showThirdView.toggle()
  28. }) {
  29. Text("How To Play")
  30. .font(.custom("Helvetica Neue", size: 25))
  31. .bold()
  32. }
  33. .buttonBorderShape(.capsule)
  34. .padding(.horizontal, 20)
  35. .padding(.vertical, 10)
  36. .foregroundColor(.white)
  37. .background(.pink)
  38. .cornerRadius(25)
  39. .contentShape(Rectangle())
  40. .navigationDestination(isPresented: $showThirdView) {
  41. ThirdView()
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48. // Preview
  49. struct ContentView_Previews: PreviewProvider {
  50. static var previews: some View {
  51. ContentView()
  52. }
  53. }

字符串

展开查看全部

相关问题