首页 > 解决方案 > 屏幕顶部的额外空间

问题描述

我正在尝试使用 SwiftUI 为我的屏幕设置背景图像。我注意到屏幕顶部大约 10 像素处有某种插图,我不确定那是什么?以及如何从最顶部开始图像。

这是我的代码:


struct AppBackGround: ViewModifier {
    
    func body(content: Content) -> some View {
             ZStack {
                Image("background")
                    .resizable()

                    .edgesIgnoringSafeArea(.all)

                    .scaledToFill()
                    .frame(width: UIScreen.main.bounds.width,
                           height: UIScreen.main.bounds.height, alignment: .top)

//                    .clipped()

                    .border(Color.red, width: 1)
                    .Print(UIScreen.main.bounds.height)
                
                content
         }

             .background(Color.red)
    }
}

extension View {
    func withAppBackground() -> some View {
        self.modifier(AppBackGround())
    }
}

struct AppBackGround_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ZStack {
                Text("iphone 8 plus")
            }
            .withAppBackground()
            .colorScheme(.light).previewDevice("iPhone 8 Plus")
            
            ZStack {
                Text("iphone 11")
            }
            .withAppBackground()
            .colorScheme(.light).previewDevice("iPhone 11")
        }
    }
}


在下图中,您可以看到图像的确切框架周围有一个红色边框。您会注意到图像顶部和屏幕顶部之间有一个空间。 8+

这也是原图,如果你想试试的话。

原来的

标签: iosswiftxcodeswiftui

解决方案


我不能确切地说那个小空间是什么,但是要修复它,您可以将 the.edgesIgnoringSafeArea(.all)从 the移动ImageZStack包含整个View:

struct AppBackGround: ViewModifier {
    

    func body(content: Content) -> some View {
             ZStack {
                Image("background")
                    .resizable()

                    // .edgesIgnoringSafeArea(.all)  // remove this

                    .scaledToFill()
                    .frame(width: UIScreen.main.bounds.width,
                           height: UIScreen.main.bounds.height, alignment: .top)

//                    .clipped()

                    .border(Color.red, width: 1)
                    .Print(UIScreen.main.bounds.height)
                
                content
         }

             .background(Color.red)
             .edgesIgnoringSafeArea(.all)   // add this
    }
}

AppBackGround可以通过制作背景的Imagean来进一步简化。这允许删除 ,因为将填满屏幕,因为.overlayColor.redframeColor.red.edgesIgnoringSafeArea(.all)

struct AppBackGround: ViewModifier {
    
    func body(content: Content) -> some View {
         ZStack {
            Color.red
                .overlay(
                    Image("background")
                        .resizable()
                        .scaledToFill()
                )
                .border(Color.red, width: 1)
            
            content
         }
         .edgesIgnoringSafeArea(.all)
    }
}

推荐阅读