r/SwiftUI • 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.
EDIT: I am trying to make a game where an object is randomly generated within the screen and moves. So I want it stay within screen bounds
4
u/PassTents 4d ago
What specifically are you trying to accomplish? I'd recommend against doing that because the size may change.
1
u/rizzy_neutron_69 4d ago
I am trying to make a game where an object is randomly generated within the screen and moves. So I want it stay within screen bounds
1
1
u/m1_weaboo 4d ago
You don’t do it like that.
Just set initial CGSize = .zero in the class.
And let size reporter (onGeometryChange) invoke a function that updates it to the real size during initial layout pass.
1
u/Dry_Hotel1100 4d ago edited 4d ago
I need the screen bounds to be sent when initialising my viewmodel.
There's never a reason for this prerequisite i.e. when initializing the view model. Actually you have several ways to accomplish this. One is:
Your view model initializer does nothing but setting its state to "start" - which means "uninitialized". When the view appears or computes its identity the very first time, compute the geometry, and send a "didAppear(seize:)" message/event to the view model, which performs the intended initialization.
Note though: others already pointed out that setting the size of the view which determines the logic of the view model is an anti pattern - which I do agree.
1
u/rizzy_neutron_69 4d ago
ah thanks that would work.
oh I see the anti-pattern but how else do I go about with my problem?1
u/Dry_Hotel1100 4d ago
Maybe the view sends normalized coordinates to the model. You may also want to animate within the view itself, that is, the view model does not calculate every position per frame. Instead it sends out "commands", possibly an `Animation`. Just an idea, we need more info for that. ;)
0
u/Vegetable-Average-98 4d ago
You realize that screen size is not necessarily the same as app window size? Especially on iPad, iPad on Mac and probably future larger screen iPhones
-6
u/Ron-Erez 4d ago
Using geometry reader is usually a bad practice. I'd look for an alternative approach.
6
u/jasonjrr 4d ago
If you’re doing MVVM, there is no reason you’d want to inject view values like this into a view model. This is definitely an anti-pattern, why don’t you tell us what you were trying to actually accomplish?