Get Parent Size SwiftUI

2019-08-20 09:40发布

问题:

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

回答1:

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.

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

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.

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



标签: swiftui