SwiftUI - Get size of child?

前端 未结 4 1146
死守一世寂寞
死守一世寂寞 2020-12-15 08:32

Is there any way to get the size of a child view in SwiftUI?

I\'m basically looking to do the UIKit equivalent of:



        
4条回答
  •  一向
    一向 (楼主)
    2020-12-15 09:28

    Here's a reusable variant of the accepted answer:

    protocol SizeReaderKey: PreferenceKey where Value == CGSize {}
    
    extension SizeReaderKey {
        static func reduce(value _: inout CGSize, nextValue: () -> CGSize) {
            _ = nextValue()
        }
    }
    
    struct SizeReader: ViewModifier {
        func body(content: Content) -> some View {
            content
                .background(
                    GeometryReader { geo in
                        Color.clear
                            .preference(key: Key.self, value: geo.size)
                    }
                )
        }
    }
    
    extension View {
        func onSizeChanged(
            _ key: Key.Type,
            perform action: @escaping (CGSize) -> Void) -> some View
        {
            self
                .modifier(SizeReader())
                .onPreferenceChange(key) { value in
                    action(value)
                }
        }
    }
    

    Usage:

    struct Example: View {
        var body: some View {
            Text("Hello, World!")
                .onSizeChanged(CustomViewSizeKey.self) { size in
                    print("size: \(size)")
                }
        }
    
        struct CustomViewSize: SizePreferenceKey {
            static var defaultValue: CGSize = .zero
        }
    }
    

提交回复
热议问题