首页 > 解决方案 > 为什么滚动视图不在顶部?

问题描述

我尝试使用 ZStack 在里面放置背景图像和滚动视图

struct DetailView: View {
    
    var body: some View {
        
        GeometryReader { geometry in
            // ZStack: Background, ScrollView(vertical)
            ZStack {
                
                Image("background_brown").resizable()
                    .aspectRatio(geometry.size, contentMode: .fill)
                    .edgesIgnoringSafeArea(.all)
                    .frame(width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
                    .border(Color.yellow, width: borderWidth)
                
                ScrollView(.vertical/, showsIndicators: true, content: {
                    
                   Text("hello")
                }).frame(width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
                .border(Color.yellow, width: borderWidth)
                
               
            }
        }
    }
}

但是,我发现滚动视图底部超出了屏幕范围。为什么会这样?

在此处输入图像描述

标签: swiftui

解决方案


这是因为您将 ZStack 中的项目设置为具有 UIScreen.main.bounds.height 的框架。因此ZStack,包括安全区域的 ,从顶部安全区域开始,并将其高度调整为UIScreen.main.bounds.height

在您的代码中,您可能只使用geometry.size.height而不是UIScreen.main.bounds.height框架,它会起作用。但是,您可以改为使用.background修饰符,如下所示:

struct DetailView2: View {
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: true, content: {
            Text("hello")
        })
        .frame(maxWidth: .infinity)
        .background(
            GeometryReader { geometry in
                Image("background_brown").resizable()
                    .aspectRatio(contentMode: .fill)
                    .edgesIgnoringSafeArea(.all)
                    .frame(width: geometry.size.width, height: geometry.size.height)
            }
        )
    }
}

推荐阅读