How to Make a Custom Geometryreader in Swiftui

SwiftUI GeometryReader does not layout custom subviews in center

Update: retested with Xcode 13.3 / iOS 15.4

Try the following (built-in container by default expanded to size of GeometryReader and have explicit default alignment set to center by both dimensions). Tested with Xcode 11.2.

var body: some View {
GeometryReader { geometry in
VStack { // explicit container with center default alignment
ImageContent()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}

How to align properly with GeometryReader in SwiftUI

You don't need GeometryReader for that, but use alignment, like

VStack {
Text("Test 3")
Text("Test 4")
}
.frame(maxWidth: .infinity, alignment: .leading) // << here !!

and get rid of unused GR.

GeometryReader behavior in SwiftUI

Uh, I am surprised to see that. Actually in Xcode 11.4 the default alignment for the GeometryReader is .center, however in Xcode 12 beta 3, the default alignment looks top-leading.

I have not seen any related information yet. However I can suggest wrapping Text into VStack or HStack and providing frame from proxy. It will provide better layout organization, in my opinion of course.

struct ContentView: View {
var body: some View {
VStack {
GeometryReader { proxy in
VStack {
Text("First Stack")
.foregroundColor(.black)
.font(.largeTitle)
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .center)
}
.background(Color.red.opacity(0.4))
Text("Second Stack").background(Color.blue)
}
.background(Color.yellow.opacity(0.5))
} }

SwiftUI - How to get GeometryReader size/height from different View?

You can:

  1. Make a @State property to store the height
  2. Set it using an .onAppear { attached to Color.clear
  3. Replace ??? with \(textHeight)
struct ContentView: View {
@State var textHeight = CGFloat(0) /// 1.

var body: some View {
VStack {
Text("Hello world!")
.background(
GeometryReader { proxy in
Color.clear
.onAppear { /// 2.
textHeight = proxy.size.height
}
}
)
/// 3.
Text("Height of first text is \(textHeight)")
}
}
}

Result:

"Hello world!" above "Height of first text is 20.333333"

How to Align GeometryReader in SwiftUI?

It looks like you placed .frame modifier in wrong place (placement of modifier is important)

Here is modified code (assuming I understood your intention)

demo

var body: some View {
GeometryReader { geo in
Text("\(randomRoll)")
.font(.title)
.padding(.horizontal)
.frame(maxWidth: .infinity, maxHeight: .infinity) // << before background !!
.background(
Rectangle()
.foregroundColor(Color(hue: min(1, geo.frame(in: .global).minY/CGFloat(randomNumber) ), saturation: 1, brightness: 1))
.cornerRadius(10))

}
.frame(height: 150)
}


Related Topics



Leave a reply



Submit