本文介绍了获取CGRect视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RectGetter获取视图 CGRect

I'm using a "RectGetter" to get the CGRect of a View.

就像这样:

Text("Hello")
    .background(RectGetter(rect: self.$rect))


struct RectGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        GeometryReader { proxy in
            self.createView(proxy: proxy)
        }
    }

    func createView(proxy: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = proxy.frame(in: .global) // crash here
        }

        return Rectangle().fill(Color.clear)
    }
}

但有时我

Thread 0 name:
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x00000001a1ec5ec4 __pthread_kill + 8
1   libsystem_pthread.dylib         0x00000001a1de5724 pthread_kill$VARIANT$armv81 + 216 (pthread.c:1458)
2   libsystem_c.dylib               0x00000001a1d358c0 __abort + 112 (abort.c:147)
3   libsystem_c.dylib               0x00000001a1d35850 abort + 112 (abort.c:118)
4   AttributeGraph                  0x00000001cce56548 0x1cce25000 + 202056
5   AttributeGraph                  0x00000001cce2b980 0x1cce25000 + 27008
6   SwiftUI                         0x00000001d89ce9b4 $s7SwiftUI27_PositionAwareLayoutContextV10dimensionsSo6CGSizeVvg + 56 (<compiler-generated>:0)
7   SwiftUI                         0x00000001d8a43584 $sSo6CGSizeVIgd_ABIegr_TRTA + 24 (<compiler-generated>:0)
8   SwiftUI                         0x00000001d8a43a54 $s7SwiftUI13GeometryProxyV4sync33_4C4BAC551E328ACCA9CD3748EDC0CC3ALLyxSgxyXElFxAA9ViewGraphCXEfU_... + 92 (GeometryReader.swift:126)
9   SwiftUI                         0x00000001d8a43f20 $s7SwiftUI13GeometryProxyV4sync33_4C4BAC551E328ACCA9CD3748EDC0CC3ALLyxSgxyXElFxAA9ViewGraphCXEfU_... + 20 (<compiler-generated>:0)
10  SwiftUI                         0x00000001d8c4842c $s7SwiftUI16ViewRendererHostPAAE06updateC5Graph4bodyqd__qd__AA0cG0CXE_tlF + 80 (ViewRendererHost.swift:64)
11  SwiftUI                         0x00000001d8a438d4 $s7SwiftUI13GeometryProxyV5frame2inSo6CGRectVAA15CoordinateSpaceO_tF + 196 (GeometryReader.swift:125)
12  MyApp                           0x0000000102cf5c54 closure #1 in RectGetter.createView(proxy:) + 128 (RectGetter.swift:22)

是否有一些更可靠的方法(不会崩溃)来获取<$ 视图的c $ c> CGRect ?

Is there some more reliable way (not crashing) to get the CGRect of a View?

推荐答案

我使用这种功能。自Xcode 11.1起有效

I use such function. Works since Xcode 11.1

func rectReader(_ binding: Binding<CGRect>) -> some View {
    return GeometryReader { (geometry) -> AnyView in
        let rect = geometry.frame(in: .global)
        DispatchQueue.main.async {
            binding.wrappedValue = rect
        }
        return AnyView(Rectangle().fill(Color.clear))
    }
}

用法相同

Text("Test").background(rectReader($rect))

这篇关于获取CGRect视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 02:16