首页 > 解决方案 > 向其添加填充时,SwiftUI 按钮没有响应

问题描述

    struct ContactView: View {
    
    @Binding var isContactViewActive: Bool
    @State var searchBar = ""
    
    var backgroundColor = Color(red: 14/255, green: 18/255, blue: 23/255, opacity: 1.0)
    
    var body: some View {
        NavigationView {
            ZStack {
                backgroundColor
                VStack {
                    HStack {
                        Button(action: {}, label: {
                            Image(systemName: "magnifyingglass").font(.title)
                        })
                        Spacer()
                        Text("FireChat")
                            .font(.title)
                            .fontWeight(.light)
                            .foregroundColor(Color.white)
                        Spacer()
                        Button(action: {}, label: {
                            Image(systemName: "power").font(.title)
                        })
                    }.padding(.top, 50)
                    Spacer()
                }
            }.edgesIgnoringSafeArea(.all)
        }
    }
}

当我尝试在我的 HStack 周围添加 padding(.top, 50) 以将其定位得更低时,我的按钮在图像区域停止响应并且只能在上面的填充区域上单击。我不明白为什么会这样,我怎样才能把我的 HStack 放低而不影响按钮的点击区域。

标签: iosswiftxcodeswiftui

解决方案


要清楚这是我用于测试的代码:

    @main
    struct TestApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    
struct ContactView: View {
    
    @Binding var isContactViewActive: Bool
    @State var searchBar = ""
    
    var backgroundColor = Color(red: 14/255, green: 18/255, blue: 23/255, opacity: 1.0)
    
    var body: some View {
        NavigationView {
            ZStack {
                backgroundColor
                VStack {
                    HStack {
                        Button(action: {print("magnifyingglass")}, label: {
                            Image(systemName: "magnifyingglass").font(.title)
                        })
                        Spacer()
                        Text("FireChat")
                            .font(.title)
                            .fontWeight(.light)
                            .foregroundColor(Color.white)
                        Spacer()
                        Button(action: {print("power")}, label: {
                            Image(systemName: "power").font(.title)
                        })
                    }.padding(.top, 50)
                }
            }.edgesIgnoringSafeArea(.all)
        }
    }
}

struct ContentView: View {
    @State var isContactViewActive = false
    var body: some View {
        ContactView(isContactViewActive: $isContactViewActive)
    }
}

推荐阅读