ignoresSafeArea 不覆盖视图底部

时间:2021-04-30 01:10:37

标签: swiftui

我正在尝试为弹出窗口的背景视图创建背景,但是即使在我使用 .ignoreSafeArea() 之后,视图也没有覆盖底部。

import SwiftUI

struct Overlay<Content: View>: View {

    @State var opacity: Double = 0
    var content: Content

    var body: some View {
        VStack {
            Color.black.opacity(opacity).ignoresSafeArea()
            content
        }
        .onAppear { self.opacity = 0.5 }
        .onDisappear { self.opacity = 0 }
    }
}

struct ForgotPasswordView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            Overlay(content: Text(""))
                .previewDevice("iPhone 12")
        }
    }
}

enter image description here

2 个答案:

答案 0 :(得分:1)

VStack 将其子项排列在一条垂直线上。

您在底部区域看到的是您在创建视图时传递的内容(这里是您的 TextView)。

struct Overlay<Content: View>: View {

    @State var opacity: Double = 0
    var content: Content

    var body: some View {
        ZStack { //<- here
            Color.black.opacity(opacity).ignoresSafeArea()
            content
        }
        .onAppear { self.opacity = 0.5 }
        .onDisappear { self.opacity = 0 }
    }
}

答案 1 :(得分:1)

这是我能够想出的解决方案:

import SwiftUI

struct Overlay<Content: View>: View {

    @State var opacity: Double = 1
    var content: Content

    var body: some View {
        VStack {
            Color.black
                .opacity(0)
            content
        }
        .background(Color.black.opacity(opacity))
        .ignoresSafeArea(.all)
        .onAppear { self.opacity = 0.5 }
        .onDisappear { self.opacity = 0 }
    }
}

struct ForgotPasswordView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            Overlay(content: Text("hi"))
                .previewDevice("iPhone 12")
        }
    }
}

Here is an image of it working 如果您希望 content 覆盖在视图的顶部,您可以使用 ZStack,颜色在后面,内容在前面。这可以通过删除 VStack 中的 V 并将其替换为 Z 来实现。Beutiful image of it working!