SwiftUI GeometryReader 不会在中心布局自定义子视图 [英] SwiftUI GeometryReader does not layout custom subviews in center

查看:27
本文介绍了SwiftUI GeometryReader 不会在中心布局自定义子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图:

struct ImageContent: View {
    var body: some View {
        Image("smile")
            .resizable()
            .scaledToFit()
    }
}

使用 GeometryReader 将其放入另一个视图中:

Which is being placed into another view with a GeometryReader:

var body: some View {
    GeometryReader { geometry in
        ImageContent()
        //Image("smile").resizable().scaledToFit()
    }
}

问题是,ImageContent 视图不是在屏幕上居中,而是放在顶部,但是,通过删除 ImageContent 子视图并直接添加查看几何阅读器的内容将解决问题(见图).

The problem is, the ImageContent view is not centered on the screen, it is being placed on the top, however, by removing the ImageContent subview and directly adding the view's content into the geometry reader will fix the issue (see picture).

此外,删除 GeometryReader 也可以解决此问题.

Also, removing the GeometryReader can fix the issue as well.

我需要子视图,因为我将实现一些额外的逻辑,还需要 GeometryReader,因为在使用它的 Image 中添加了一个手势.

I need the subview because I will be implementing some additional logic, and also need the GeometryReader because there is a gesture added to the Image that uses it.

有什么想法吗?

推荐答案

请尝试以下操作(默认情况下,内置容器扩展为 GeometryReader 的大小,并通过两个维度将显式默认对齐设置为居中).使用 Xcode 11.2 测试.

Try the following (built-in container by default expanded to size of GeometryReader and have explicit default alignment set to center by both dimensions). Tested with Xcode 11.2.

var body: some View {
    GeometryReader { geometry in
       VStack { // explicit container with center default alignment
        ImageContent()
       }
    }
}

这篇关于SwiftUI GeometryReader 不会在中心布局自定义子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆