why geometry reader doesn't center its child? - swift

red border is geometry Area and black border is text area
currently using Xcode12 Beta 3
struct Testing_Geometry_: View {
var body: some View {
GeometryReader { geo in
Text("Hello, World!")
.border(Color.black)
}
.border(Color.red)
}
}
I wanted to position text in center with this code
struct Testing_Geometry_: View {
var body: some View {
GeometryReader { geo in
Text("Hello, World!")
.position(x:geo.frame(in:.global).midX,y:geo.frame(in:.global).midY)
.border(Color.black)
}
.border(Color.red)
}
}
but I got this result which means Text is taking the whole geometry size and I think it's not correct!
cause texts has to fit in their space
three roles suggested by #twostraws for layout systems are
1- parent offers its size
2-child chooses its size
3-parent positions its child
but I think this isn't right!
text is taking the whole geometry space

If someone is looking for basic solution, you can put it in one of Stack and make it use whole size of geometry size with alignment center. That will make all elements underneath to use correct size and aligned in center
GeometryReader { geometry in
ZStack {
// ... some of your views
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
}

The problem is that modifier order matters, because modifiers actually create parent views. I've used backgrounds instead of borders because I think they're easier to see. Consider this code that's the same as yours but just using a background:
struct TestingGeometryView: View {
var body: some View {
GeometryReader { geo in
Text("Hello, World!")
.position(x:geo.frame(in:.global).midX,y:geo.frame(in:.global).midY)
.background(Color.gray)
}
.background(Color.red)
}
}
This gives the following:
From this you are thinking "Text is taking the whole geometry size and I think it's not correct!" because the gray background is taking the whole screen instead of just around the Text. Again, the problem is modifier order- the background (or border in your example) is a parent view, but you are making it the parent of the "position" view instead of the Text view. In order for position to do what it does, it takes the entire parent space available (in this case the whole screen minus safe area). So putting background or border as parent of position means they will take the entire screen.
Let's switch the order to this, so that background view is only for the Text view and we can see size of Text view:
struct TestingGeometryView: View {
var body: some View {
GeometryReader { geo in
Text("Hello, World!")
.background(Color.gray)
.position(x:geo.frame(in:.global).midX,y:geo.frame(in:.global).midY)
}
.background(Color.red)
}
}
This gives the result I think you were expecting with the Text view only taking up the minimum size required, and following those rules that #twostraws explained so nicely.
This is why modifier order is so important. It's clear that GeometryReader view is taking up the entire screen, and Text view is only taking up the space it requires. In your example, Text view was still only taking up the required space but your border was around the position view, not the Text view. Hope it's clear :-)

Related

Why does SwiftUI View background extend into safe area?

Here's a view that navigates to a 2nd view:
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink {
SecondView()
} label: {
Text("Go to 2nd view")
}
}
}
}
struct SecondView: View {
var body: some View {
ZStack {
Color.red
VStack {
Text("This is a test")
.background(.green)
//Spacer() // <--If you add this, it pushes the Text to the top, but its background no longer respects the safe area--why is this?
}
}
}
}
On the 2nd screen, the green background of the Text view only extends to its border, which makes sense because the Text is a pull-in view:
Now, if you add Spacer() after the Text(), the Text view pushes to the top of the VStack, which makes sense, but why does its green background suddenly push into the safe area?
In the Apple documentation here, it says:
By default, SwiftUI sizes and positions views to avoid system defined
safe areas to ensure that system content or the edges of the device
won’t obstruct your views. If your design calls for the background to
extend to the screen edges, use the ignoresSafeArea(_:edges:) modifier
to override the default.
However, in this case, I'm not using ignoresSafeArea, so why is it acting as if I did, rather than perform the default like Apple says, which is to avoid the safe areas?
You think that you use old background modifier version.
But actually, the above code uses a new one, introduced in iOS 15 version of background modifier which by default ignores all safe area edges:
func background<S>(_ style: S, ignoresSafeAreaEdges edges: Edge.Set = .all) -> some View where S : ShapeStyle
To fix the issue just replace .background(.green) with .background(Color.green) if your app deployment target < iOS 15.0, otherwise use a new modifier: .background { Color.green }.

Forcing a View to the bottom right of View in SwiftUI

I'm teaching myself SwiftUI by taking the 2020 version of Stanford's CS193p posted on YouTube.
I'd like to have a ZStack with a check box in the bottom right. This code puts the check mark
right in the middle of the View.
ZStack {
.... stuff ....
Text("✓")
}
Much to my surprise, this code puts the check mark in the top left corner of the View. (My mental model of GeometryReader is clearly wrong.)
ZStack {
.... stuff ...
GeometryReader { _ in Text("✓") }
}
I can't use ZStack(alignment: .bottomTrailing) { ... } as suggested in a different StackOverflow answer, as I want the alignment to apply only to the text, and not to anything else.
Is there any way to get the check mark on the bottom right? I'm trying to avoid absolute offsets, since I want my code to work no matter what the size of the ZStack view. Also, is there a good tutorial on layout so that I can figure out the answer to these questions myself?
[In case you're wondering. I'm playing around with Homework Assignment 3. I'm adding a "cheat mode" where if there is a matchingSet on the board, it marks them with a small check mark.]
Try applying
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
to Text.
I would say that it's possible if you know the size of the Text and the largest subview in the ZStack.
In the example below I've used 40 as the Text width and 20 as the Text height, and 200 (square) for the largest Color subview. You can then calculate the subview offsets using relative offsets and layout guides.
This is useful if you don't want to expand the Text to fill the container like the above answer.
struct ColorsView: View {
var body: some View {
ZStack(alignment: .center) {
Color.red.frame(width: 200,
height: 200,
alignment: .center)
Text("Bye")
Text("Hello").frame(width: 40, height: 20)
.alignmentGuide(HorizontalAlignment.center, computeValue: { dimension in
-60
})
.alignmentGuide(VerticalAlignment.center, computeValue: { dimension in
-80
})
}
}
}

SwiftUI Zstack – Make element ignore safe area and another one don't

I have a Zstack like this:
ZStack {
Image("beach")
.resizable()
.edgesIgnoringSafeArea(.all)
.scaledToFill()
VStack {
// with a lot of stuff
}
}
I want the image to ignore the safe area, but the Vstack must respect the safe area.
The image is a background image that should cover all the area.
This code I have is making the VStack full screen too and I don't want that.
Why everything is not respecting the safe area is a mystery, because the respective modifier is applied to the image only.
Put your image in the .background:
struct ContentView: View {
var body: some View {
VStack {
// lots of stuff
Color.red
Color.blue
}
.background(
Image("beach")
.resizable()
.edgesIgnoringSafeArea(.all)
.scaledToFill()
)
}
}
The reason why it doesn't work with your example is that you are using scaledToFill() modifier on image, and here it matters in this particular case.
First you declared ZStack which is itself doesn't ignore safe area. After you put Image and resizable. What resizable does, is it stretches the image to fit its view, in your case it is the ZStack.
Let's see what we have until now.We have an image which stretches till the safe area.
ZStack {
Image("Breakfast").resizable()
}
So from now on you put edgesIgnoringSafeArea on Image, which lets the image cover all the area(ignore safe area).
Now you have Zstack which respects safe area, and Image which ignores safe area. This let you put VStack in ZStack and add staff inside it. VStack will fill its parent view, which is ZStack, so it too will respect safe area(See code and image below).
ZStack {
Image("Breakfast").resizable().edgesIgnoringSafeArea(.all)
VStack {
Text("hello")
Spacer()
}
}
And here at last you add .scaledToFill() modifier, which stretches the image to contain all the area, and by doing this it makes ZStack view to become the hole area, as fitting view's (ZStack, HStack, VStack) calculates its size based on its content.
Useful link:
Fitting and filling views in SwiftUI
How to resize a SwiftUI Image and keep its aspect ratio
Another way that worked for me is:
struct ContentView: View {
var body: some View {
ZStack {
Color.clear
.background(
Image("beach")
.resizable()
.ignoresSafeArea()
.scaledToFill()
)
VStack {
// lots of stuff
}
}
}
}
Note: In my case, when trying the other solution of putting .background on VStack the image did not fill the entire screen, instead it shrank to fit the size of what was in the VStack.

How to use GeometryReader within a LazyVGrid

I'm building a grid with cards which have an image view at the top and some text at the bottom. Here is the swift UI code for the component:
struct Main: View {
var body: some View {
ScrollView {
LazyVGrid(columns: .init(repeating: .init(.flexible()), count: 2)) {
ForEach(0..<6) { _ in
ZStack {
Rectangle()
.foregroundColor(Color(UIColor.random))
VStack {
Rectangle()
.frame(minHeight: 72)
Text(ipsum)
.fixedSize(horizontal: false, vertical: true)
.padding()
}
}.clipShape(RoundedRectangle(cornerRadius: 10))
}
}.padding()
}.frame(width: 400, height: 600)
}
}
This component outputs the following layout:
This Looks great, but I want to add a Geometry reader into the Card component in order to scale the top image view according to the width of the enclosing grid column. As far as I know, that code should look like the following:
struct Main: View {
var body: some View {
ScrollView {
LazyVGrid(columns: .init(repeating: .init(.flexible()), count: 2)) {
ForEach(0..<6) { _ in
ZStack {
Rectangle()
.foregroundColor(Color(UIColor.random))
VStack {
GeometryReader { geometry in
Rectangle()
.frame(minHeight: 72)
Text(ipsum)
.fixedSize(horizontal: false, vertical: true)
.padding()
}
}
}.clipShape(RoundedRectangle(cornerRadius: 10))
}
}.padding()
}.frame(width: 400, height: 600)
}
}
The trouble is that this renders as the following:
As you can see, I'm not even trying to use the GeometryReader, I've just added it. If I add the geometry reader at the top level, It will render the grid correctly, however this is not of great use to me because I plan to abstract the components into other View conforming structs. Additionally, GeometryReader seems to be contextually useful, and it wouldn't make sense to do a bunch of math to cut the width value in half and then make my calculations from there considering the geometry would be from the top level (full width).
Am I using geometry reader incorrectly? My understanding is that it can be used anywhere in the component tree, not just at the top level.
Thanks for taking a look!
I had the same problem as you, but I've worked it out. Here's some key point.
If you set GeometryReader inside LazyVGrid and Foreach, according to SwiftUI layout rule, GeometryReader will get the suggested size (may be just 10 point). More importantly, No matter what subview inside GeometryReader, it wouldn't affect the size of GeometryReader and GeometryReader's parent view.
For this reason, your view appears as a long strip of black. You can control height by setting GeometryReader { subView }.frame(some size),
Generally, we need two GeometryReader to implement this. The first one can get size and do some Computing operations, then pass to second one.
(Since my original code contains Chinese, it may be hard for you to read, so I can only give a simple structure for you.)
GeometryReader { firstGeo in
LazyVGrid(columns: rows) {
ForEach(dataList) { data in
GeometryReader { secondGeo in
// subview
}
.frame(width: widthYouWantSubViewGet)
}
}
}
I just started to learn swift for a week. There may be some mistakes in my understanding. You are welcome to help correct it.

How can I get a SwiftUI View to completely fill its superview?

The following is supposed to create a Text whose bounds occupy the entire screen, but it seems to do nothing.
struct ContentView: View {
var body: some View {
Text("foo")
.relativeSize(width: 1.0, height: 1.0)
.background(Color.red)
}
}
The following hack:
extension View {
/// Causes the view to fill into its superview.
public func _fill(alignment: Alignment = .center) -> some View {
GeometryReader { geometry in
return self.frame(
width: geometry.size.width,
height: geometry.size.height,
alignment: alignment
)
}
}
}
struct ContentView2: View {
var body: some View {
Text("foo")
._fill()
.background(Color.red)
}
}
seems to work however.
Is this a SwiftUI bug with relativeSize, or am I missing something?
You need to watch WWDC 2019 Session 237: Building Custom Views with SwiftUI, because Dave Abrahams discusses this topic, and uses Text in his examples.
To restate briefly what Dave explains in detail:
The parent (in this case, a root view created by the system and filling the screen) proposes a size to its child.
The child chooses its own size, consuming as much or as little of the proposed size as it wants.
The parent positions the child in the parent’s coordinate space based on various parameters including the size chosen by the child.
Thus you cannot force a small Text to fill the screen, because in step 2, the Text will refuse to consume more space than needed to fit its content.
Color.red is different: in step 2, it just returns the proposed size as its own size. We can call views like this “expandable”: they expand to fill whatever space they're offered.
ZStack is also different: in step 2, it asks its children for their sizes and picks its own size based on its children's sizes. We can call views like this “wrapping”: they wrap their children tightly.
So if you promote Color.red to be the “main” view returned by body, and put the Text in an overlay, your ContentView will behave like Color.red and be expandable:
struct ContentView: View {
var body: some View {
Color.red
.overlay(Text("foo"))
}
}
If you use a ZStack containing both Color.red and Text, the ZStack will wrap the Color.red, and thus take on its expandability:
struct ContentView: View {
var body: some View {
ZStack {
Color.red
Text("hello")
}
}
}