如何使用几何阅读器使视图不扩展?

iOS*_*com -1 swiftui

我用过这样的几何阅读器

GeometryReader { r in
   ScrollView {
      Text("SomeText").frame(width: r.size.width / 2)
   }
}
Run Code Online (Sandbox Code Playgroud)

问题是阅读器垂直扩展很像Spacer(). 无论如何,我可以让它这样做吗?

iOS*_*com 5

谷歌搜索后,我在这里找到了这个答案。

创建这个新结构

struct SingleAxisGeometryReader<Content: View>: View {
    private struct SizeKey: PreferenceKey {
        static var defaultValue: CGFloat { 10 }
        static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
            value = max(value, nextValue())
        }
    }

    @State private var size: CGFloat = SizeKey.defaultValue
    var axis: Axis = .horizontal
    var alignment: Alignment = .center
    let content: (CGFloat)->Content

    var body: some View {
        content(size)
            .frame(maxWidth:  axis == .horizontal ? .infinity : nil,
                   maxHeight: axis == .vertical   ? .infinity : nil,
                   alignment: alignment)
            .background(GeometryReader {
                proxy in
                Color.clear.preference(key: SizeKey.self, value: axis == .horizontal ? proxy.size.width : proxy.size.height)
            }).onPreferenceChange(SizeKey.self) { size = $0 }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

SingleAxisGeometryReader { width in  // For horizontal
   // stuff here
}
Run Code Online (Sandbox Code Playgroud)

或者

SingleAxisGeometryReader(axis: .vertical) { height in  // For vertical
   // stuff here
}
Run Code Online (Sandbox Code Playgroud)

有了这个答案,它现在是通用的,无需更改代码。