首页 > 解决方案 > SwiftUI - 获取孩子的大小?

问题描述

有没有办法在 SwiftUI 中获取子视图的大小?

我基本上希望做的 UIKit 相当于:

self.child.frame.origin.x -= self.child.intrinsicContentSize.width/2.0

我认为 GeometryReader 不会起作用,因为它会返回父级中的可用大小。

[编辑] 我发现使用它来获取和保存尺寸是可能的,.alignmentGuide(_, computeValue:)尽管这绝对是一个 hack。

LessonSliderText(text: self.textForProgress(self.progress), color: self.completedColor)
    .alignmentGuide(HorizontalAlignment.leading) { (dimensions) -> Length in
        self.textSize = CGSize(width: dimensions.width, height: dimensions.height)
        return 0
    }
    .offset(x: self.width*self.currentPercentage - self.textSize.width / 2.0)
    .offset(y: -self.textSize.height/2.0)
    .animation(nil)
    .opacity(self.isDragging ? 1.0 : 0.0)
    .animation(.basic())

我想要完成的事情

标签: swiftui

解决方案


更新并概括了@arsenius 代码。现在您可以轻松绑定父视图的状态变量。

struct ChildSizeReader<Content: View>: View {
    @Binding var size: CGSize
    let content: () -> Content
    var body: some View {
        ZStack {
            content()
                .background(
                    GeometryReader { proxy in
                        Color.clear
                            .preference(key: SizePreferenceKey.self, value: proxy.size)
                    }
                )
        }
        .onPreferenceChange(SizePreferenceKey.self) { preferences in
            self.size = preferences
        }
    }
}

struct SizePreferenceKey: PreferenceKey {
    typealias Value = CGSize
    static var defaultValue: Value = .zero

    static func reduce(value _: inout Value, nextValue: () -> Value) {
        _ = nextValue()
    }
}

用法:

struct ChildSizeReaderExample: View {
    @State var textSize: CGSize = .zero
    var body: some View {
        VStack {
            ChildSizeReader(size: $textSize) {
                Text("Hello I am some arbitrary text.")
            }
            Text("My size is \(textSize.debugDescription)!")
        }
    }
}

推荐阅读