首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ViewModifier中使用GeometryReader不会呈现视图

在ViewModifier中使用GeometryReader不会呈现视图
EN

Stack Overflow用户
提问于 2020-10-15 21:03:19
回答 2查看 277关注 0票数 1

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

以下代码将导致空白屏幕:

代码语言:javascript
复制
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
        }
    }
}

这种情况只发生在Xcode13上,而且只有在使用iOS 12编译代码的情况下才会发生。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-15 21:03:19

它看起来像是一个bug,所以作为一种解决办法,有两件事可以做:

1.在修饰符外部使用GeometryReader,并将代理传递给修饰符:

代码语言:javascript
复制
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中嵌入使用修饰符的视图:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2020-10-30 18:28:29

我遇到了同样的问题,不得不完全放弃使用ViewModifier,转而使用在扩展中使用视图包装的旧方法:

代码语言:javascript
复制
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)
        }
    }
}

谢谢你@奥列格-谢尔曼证实了我的怀疑!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64372192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档