首页 > 解决方案 > SwiftUI onTapGuesture 不能在 ZStack 中使用偏移量?

问题描述

我在 ZStack 中有一个 Mapbox 地图视图和一个搜索栏和激活按钮(HStack),并使用偏移修改器将它们定位在屏幕顶部。

由于某种原因,偏移量会阻止 onTapGesture 为激活按钮工作,如果我注释掉偏移量,它将起作用,但将放置在屏幕底部。

我尝试将偏移量单独添加到 HStack 内的每个元素,但这不起作用......

如何使 onTapGesture 功能与偏移量一起使用?

谢谢

struct MapScreen: View {
        
    var body: some View {
        NavigationView {
            ZStack(alignment: .bottom) {
                HStack(spacing: 10) {
                    SearchBar()
                        .padding(.leading, 5)
                        .onTapGesture {
                            print("search pressed")
                           
                        }
                    ActivateButton()
                        .onTapGesture {
                            print("activate pressed")
                        }
                }.zIndex(2)
                .offset(y: -770)
                MapView(locations: $locations)
                  .edgesIgnoringSafeArea([.top, .bottom])
                BottomNavBar().zIndex(1)
                  .edgesIgnoringSafeArea(.all).offset(y: 35)
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .fullScreenCover(isPresented: $presentSearchView, content: {
                SearchView()
             })
        }
    }
}

标签: iosswiftui

解决方案


这里有几个问题:

.offset(y: -770)

如果您尝试使用offset如此大的值,则根本不应该使用偏移量。offset通常用于微调调整,不适用于大值。而且,770是硬编码的。当您使用具有不同屏幕尺寸的另一台设备时会发生什么?不要自己硬编码或进行计算 - SwiftUI 可以为您完成!

相反,使用VStack+Spacer()向上推搜索栏。

ZStack(alignment: .bottom) {
    VStack { /// here!
        HStack(spacing: 10) {
            SearchBar()
                .padding(.leading, 5)
                .onTapGesture {
                    print("search pressed")
                    
                }
            ActivateButton()
                .onTapGesture {
                    print("activate pressed")
                }
        }
        
        Spacer() /// push the `HStack` to the top of the screen
    }
    .zIndex(2)
    
    MapView(locations: $locations)
        .edgesIgnoringSafeArea([.top, .bottom])
    BottomNavBar().zIndex(1)
        .edgesIgnoringSafeArea(.all).offset(y: 35)
}

推荐阅读