I’m trying to get continuity in my views across all device sizes but my frames are a fixed size. I need to get them to change depending on the size of the device. I have tried using Geometry Reader but it didn’t seem to work in some cases. Is Geometry Reader the only way or are there better alternatives?
This is an example of where Geometry Reader made the frame respond weirdly.
(This view is supposed to be a rectangle ’tile’)
struct ProductCardView: View {
var body: some View {
GeometryReader { geometry in
VStack {
Image("ProductImage")
Text("Product Name)
}
//MARK: Framing Before Geometry Reader .frame(width: 160, height: 210)
.frame(width: geometry.size.width * 0.40)
.frame(height: geometry.size.height * 0.27)
}
}
}
How do I make frames dynamic?
Here is how it is turning out:
2
Answers
Uses
Color.clear
to fill all screen then calculate its size usingGeometryReader
andPreferenceKey
.For
ScrollView
ScrollView
Add the following extension in some file
And whenever you want to reference a value that should be a size relative to screen width or screen height, you can call
UIScreen.screenWidth
for example. For example, your frame modifiercan now be