首页 > 解决方案 > GeometryReader 不需要的全高/全宽行为

问题描述

我使用GeometryReader来确保图像永远不会超过屏幕宽度的一半。GeometryReader但是,当请求视图的完整高度/宽度时,它会弄乱我的视图的其余部分(如带有绿色 BG 的图像所示)。好像它插入了不需要的Spacer().

struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                GeometryReader{ g in
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                    }.background(Color.yellow)
                }.background(Color.green)
            }
            Text("Bottom Text")

            // This Spacer should push the "Bottom Text" right below the other Text and Image
            Spacer()
        }
    }
}

在此处输入图像描述

如果我删除GeometryReader并将宽度设置为固定大小,它会按预期工作并且绿色 BG 不会出现。

struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                HStack{
                    Text("Text Left").background(Color.yellow)
                    Image(systemName: "checkmark")
                        .resizable()
                        .aspectRatio(contentMode:.fit)
                        .frame(maxWidth: 200)
                }.background(Color.yellow)
            }.background(Color.green)
            Text("Bottom Text")
            Spacer()
        }
    }
}

这是一个错误还是如何使用 实现动态宽度GeometryReader

在此处输入图像描述

标签: swiftui

解决方案


为什么要在 vstack 中设置几何读取器?也许你有一个理由......但这种方式,我认为,如你所愿?!

但是,是的,你是对的,几何阅读器的东西很奇怪......

 GeometryReader{ g in

            VStack{
                VStack {
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                            .background(Color.red)
                    }.background(Color.yellow)

                }
                Text("Bottom Text")

                // This Spacer should push the "Bottom Text" right below the other Text and Image
                Spacer()
            }
        }.background(Color.green)

推荐阅读