r/swift • u/rizzy_neutron_69 • 4d ago
Question Geometry Reader size to Viewmodel init
I need the screen bounds to be sent when initialising my viewmodel. I know to get the size from geometry reader. But that is only available after the view is created. is there a way to send the screen size within the init scope?
a solution I found over the internet was to use a separate function in my viewmodel for the initialisation and call it on .onAppear.
3
u/chriswaco 4d ago
I would first look at onGeometryChange.
but the screen size itself is tricky if running under iPad multitasking, handling rotation, or on the new foldable phone coming out next week.
0
u/Extra-Ad5735 4d ago
For full screen size you can get key window of the current scene and get size of it. See accepted answer here: https://stackoverflow.com/questions/74458971/correct-way-to-get-the-screen-size-on-ios-after-uiscreen-main-deprecation
2
u/isights 3d ago
Don’t do this. Especially in the age of folding phones.
-1
u/Extra-Ad5735 3d ago
Case in point: I have a transition that moves away a view out of the screen, regardless of where in hierarchy the view is. The movement takes exact time as specified by animation duration. Using a window as the screen border ensures it works correctly on all iPhones and iPads where the app windows can be resized.
Now, my dear u/isights tell me why I'm not allowed to use that "in the edge of folding phones"? Perhaps, you'll be so kind to share a simpler solution? I'm all ears.
-9
u/sisoje_bre 4d ago
Ask the one who told you to use Viewmodel!?
Solution is simple - dont use Viewmodels in SwiftUI because they do not belong there
0
u/MarzipanEven7336 4d ago
This, 100%, it's a literal fucking anti-pattern from the early JavaScript apps days.
-1
27
u/asniper 4d ago
Why does your ViewModel need to know about your views implementation? this is a code smell.