5

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

AngryDuck
  • 4,358
  • 13
  • 57
  • 91
  • 1
    You should use Geometry Reader in SwiftUI, [this](https://stackoverflow.com/questions/56729619/what-is-geometry-reader-in-swiftui/56729880#56729880) can be useful for you – Radagast Jul 09 '19 at 14:40

1 Answers1

9

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/

kontiki
  • 37,663
  • 13
  • 111
  • 125
  • very good article too btw! nice and light but has all the info I needed – AngryDuck Jul 09 '19 at 15:14
  • Thank you! I could not find that information anywhere (specially View Preferences), so after struggling to understand it and finally cracking it, I decided to contribute ;-) Cheers. – kontiki Jul 09 '19 at 15:22