在ViewModifier中使用GeometryReader不会渲染视图

时间:2020-10-15 13:03:19

标签: swiftui

我有一个自定义修饰符来处理显示/隐藏键盘,但是在iOS 13上运行时,它无法呈现视图,经过一些调查后,我发现原因是在ViewModifier中使用了GeometryReader。

以下代码将导致黑屏:

struct ContentView: View {
    var body: some View {
        Text("Foo")
            .modifier(MyCustomModifier())
    }
}

struct MyCustomModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            content
            // Use proxy
        }
    }
}

仅在iOS 13上并且仅在使用Xcode 12编译代码时才会发生。

2 个答案:

答案 0 :(得分:1)

这看起来像是个错误,因此要解决此问题,可以做两件事:

1。在修饰符之外使用GeometryReader并将代理传递给 修饰符:

struct ContentView: View {
    var body: some View {
        GeometryReader { proxy in
            Text("Foo")
                .modifier(MyCustomModifier(geometryProxy: proxy))
        }
    }
}

struct MyCustomModifier: ViewModifier {
    let geometryProxy: GeometryProxy
    
    func body(content: Content) -> some View {
        content
        // Use proxy
    }
}

2。只需将使用修饰符的视图嵌入到 GeometryReader:

struct ContentView: View {
    var body: some View {
        GeometryReader { _ in
            Text("Foo")
                .modifier(MyCustomModifier())
        }
    }
}

struct MyCustomModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            content
            // Use proxy
        }
    }
}

答案 1 :(得分:0)

我遇到了同样的问题,不得不完全放弃使用ViewModifier并改用旧的方法,并在扩展中使用视图换行:

extension View {

    /// Conditionally applies bottom padding to the view, if there's no
    /// bottom safe area inset (or if it's less than the padding provided).
    /// - Parameter padding: The min bottom padding to apply.
    @available(iOS, deprecated: 14, message: "Time to switch to the ViewModifier approach.")
    func minBottomPadding(_ padding: CGFloat) -> some View {
        // Currently there's a bug that prevents using GeometryReader inside ViewModifier on iOS 13.
        GeometryReader { geometry in
            self.padding(.bottom, geometry.safeAreaInsets.bottom < padding ? padding : 0)
        }
    }
}

感谢@ oleg-sherman证实我的怀疑!