获取父尺寸 SwiftUI [英] Get Parent Size SwiftUI

查看:23
本文介绍了获取父尺寸 SwiftUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用 SwiftUI 找到父视图的大小,我查看了文档和示例,似乎大多数(如果不是全部)都是硬编码大小,理想情况下我想找到父视图的大小然后根据父级大小的百分比设置子视图大小(可能在某些 swift helper 类或其他类中)例如

Is there any way of finding the parent view size using SwiftUI, I have had a look through the documentation and examples and it seems most (if not all) are hard coding sizes, ideally I want to find the size of the parent and then set the sub view size based on a percentage of the parents size (probably in some swift helper class or something) e.g.

func getSizeFromParent(fractionHeight: Int, fractionWidth: Int) -> Size
{
    var parentSize = // is there a way to get parent size somehow

    var newHeight = parentSize.height * fractionHeight
    var newWidth = parentSize.width * fractionWidth

    return Size(newHeight, newWidth)
}

注意上面的代码并不是一个工作示例,只是伪代码

Note the above code is not meant to be a working example just pseudo code

推荐答案

在 SwiftUI 中,父母会向他们的孩子建议尺寸,但孩子们决定如何使用它.他们可以忽略它,部分使用它,或者完全服从.

In SwiftUI parents suggest a size to their children, but children decide what to do with it. They can ignore it, use it partially, or be completely obedient.

正如 Radagast 在您的问题中评论的那样,GeometryReader 是 SwiftUI 用来在视图树层次结构中向下传达大小的方式.

As Radagast commented in your question, GeometryReader is the way SwiftUI uses to communicate sizes down the view tree hierarchy.

我写了一篇关于如何使用 GeometryReader 和 GeometryProxy 的详细文章,并包含了一些用例示例.GeometryReader 与 .background() 和 .overlay() 修饰符结合使用也非常有用,因为它可以让您窃取"另一个视图的几何形状.

I've written a detailed article about how you can use GeometryReader and GeometryProxy and I included some examples of use cases. GeometryReader is also very useful in combination with the .background() and .overlay() modifiers, as it let you "steal" the geometry of another view.

欲了解更多信息,请查看:https://swiftui-lab.com/几何阅读器到救援/

For more information, check: https://swiftui-lab.com/geometryreader-to-the-rescue/

这篇关于获取父尺寸 SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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