SwiftUI Text alignment with maxWidth not working - swift

I have the following code:
struct ContentView: View {
var body: some View {
Text("Test")
.foregroundColor(.white)
.font(.subheadline)
.frame(maxWidth: .infinity)
.alignmentGuide(.leading) { d in d[.leading] }
.background(Color(.blue))
}
}
But as you can see on the image bellow, it does not left align the text. Does anyone knows why this is happening?
Maybe because i'm using maxWidth the alignmentGuide thinks it's already left aligned?

Because alignmentGuide has effect in container with other subviews. In this case you need to align Text within own frame.
Here is solution
Text("Test")
.foregroundColor(.white)
.font(.subheadline)
.frame(maxWidth: .infinity, alignment: .leading) // << here !!
.background(Color(.blue))

Related

How to align the right side of an object to the exact middle of a view SwiftUI

I have an HStack with two Texts.
HStack {
Text("Hello")
Text("World")
}
I want Text("Hello") to be on the left side of the page and Text("World") to be on the right side of the page and for both texts to be equidistant from the exact horizontal center of the page. I added a visual for clarification:Visual
I've tried a bunch of different stuff but I haven't found any way to accomplish this task precisely.
You can use the alignment argument of the frame modifier.
Spacing argument for the HStack is for the spacing in between the texts.
HStack(spacing: 0) {
Text("Hello, World!")
.frame(maxWidth: .infinity, alignment: .trailing)
Text("Hello, World!")
.frame(maxWidth: .infinity, alignment: .leading)
}
I really didn't understand your need but according to your drawing I think you need something like below,
HStack{
Spacer()
Text("Hello")
.background(Color.orange)
Spacer().frame(width: 20)
Text("World")
.background(Color.orange)
Spacer()
}

How to make a clear SwiftUI view block the scrollview underneath it

So I have a ZStack that contains a ScrollView on the bottom and an HStack that's aligned at the top. It looks something like this:
ZStack {
ScrollView {
//Content
}
VStack {
HStack {
Spacer()
Circle()
.frame(width: 30, height: 30)
Spacer()
}
Spacer()
}
}
Now, I want that HStack to block any interaction with the ScrollView beneath it. I've noticed that when I set the background on the HStack to a non-clear color, it behaves as I'd like it to. However, if the background is clear, then the touches go through the HStack and interact with the ScrollView beneath it. I've also tried using .allowsHitTesting(true) on the HStack with no luck.
Any help is much appreciated!
https://i.stack.imgur.com/5Jzby.png
"...I've noticed that when I set the background on the HStack to a non-clear color, it behaves as I'd like it to.", then you could use Color.white.opacity(0.001)
instead of Color.clear or non-clear color
You can easily accomplish this by putting it in a VStack instead of a ZStack. The touches will be ignored as it's above the ScrollView. You can also have a look at .layoutPriority(), it may also be useful. Documentation is here.
struct ContentView: View {
var body: some View {
VStack {
HStack {
Spacer()
Circle()
.foregroundColor(Color.blue)
.frame(width: 30, height: 30)
Spacer()
}
.padding()
// or this does the same thing as the HStack two spacers
/*
Circle()
.foregroundColor(Color.blue)
.frame(width: 30, height: 30)
.frame(minWidth: 0, maxWidth: .infinity)
*/
Spacer()
ScrollView {
ForEach(1..<11) { value in
Text("\(value)")
}
}
}
}
}

Align heights of HStack members

I want to align the heights of two HStack members. The expected outcome would be that the image has the same size as the text. The current outcome is that the image has more height than the text. This is my current setup:
HStack {
Text("Sample")
.font(.largeTitle)
.padding()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
)
Spacer()
Image(systemName: "checkmark.seal.fill")
.resizable()
.scaledToFit()
.padding()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
)
}
What I've tried:
.fixedSize() -> I tried to tack this modifier onto the Image but the result was that the Image's height got smaller than the text's. Probably because the SFSymbol's intrinsic height is smaller than the .largeTitle intrinsic height.
AlignmentGuide -> I tried to create a custom alignment guide where I initially thought I could say "align bottom of Image and Text and align top of Image and Text" and therefore have the same height. But it seemed like you can only apply a single alignment guide per stack view.
GeometryReader -> I tried to wrap the HStack in a GeometryReader in which I tacked the .frame(height: proxy.frame.height) view modifier on the Text and Image. This also did not help because it somehow just made some white space around the views.
How it is:
How I want it:
Wrap your Image in a Text. Since your image is from SF Symbols, SwiftUI will scale it to match the dynamic type size. (I'm not sure how it will scale other images.)
VStack {
let background = RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
ForEach(Font.TextStyle.allCases, id: \.self) { style in
HStack {
Text("\(style)" as String)
.padding()
.background(background)
Spacer()
Text(Image(systemName: "checkmark.seal.fill"))
.padding()
.background(background)
}
.font(.system(style))
}
}
You can get the size of the Image small by adding a .frame() modifier to your HStack. See the code below,
HStack {
// Some Content
}
.frame(height: 60) // Interchangeable with frame(maxHeight: 60)
The Result:
For your exact example, I found 60 to be the sweet spot. But if you wanted a more dynamic solution, I'd make a few changes to your code. See the code below.
HStack {
Text("Sample")
.font(.largeTitle)
.frame(maxHeight: .infinity) // force the text to take whatever height given to the Parent View, which is the HStack
.padding(.horizontal) // Add padding to the Text to the horizontal axis
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
)
Spacer()
Image(systemName: "checkmark.seal.fill")
.resizable()
.scaledToFit()
.padding()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
)
}
.background(Color.gray)
.frame(height: 100) // Change this value and the embedded Views will fit dynamically
The output will work as shown in the GIF below,
Here is an upgrade version of rob answer which support Assets Image plus system Image! Almost any Image! Like this:
struct ContentView: View {
var body: some View {
VStack {
ForEach(Font.TextStyle.allCases, id: \.self) { style in
HStack {
Text(String(describing: style))
.padding()
.background(Color.pink.opacity(0.5).cornerRadius(10.0))
Spacer()
}
.font(.system(style))
.background(
Image("swiftPunk")
.resizable()
.scaledToFit()
.padding()
.background(Color.yellow.cornerRadius(10.0))
, alignment: .trailing)
}
}
}
}
Result:

How to move this to the top?

I just learned how to implement specific rounded corners, but now it seems nothing will align to the top of the screen, even with spacers. How can I get it to align to the top of the screen?
Additionally, I would like the green to ignore the top safe area, but it wasn't doing that earlier either.
import SwiftUI
struct Dashboard: View {
#State var bottomLeft: CGFloat = 25
var body: some View {
ZStack {
Color("background")
.edgesIgnoringSafeArea(.all)
VStack {
VStack {
Text("Good Morning, Sarah")
.font(Font.system(size: 36))
.foregroundColor(.standaloneLabelColor)
.fontWeight(.semibold)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
Text("We're glad to see you and hope you're doing well. Let's take on the day.")
.font(Font.system(size: 20))
.foregroundColor(.standaloneLabelColor)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.padding(.bottom)
}
.background(Color.appColor)
.cornerRadius(bottomLeft, corners: .bottomLeft)
.padding(.bottom, 10)
}
Spacer()
}
}
}
Thanks in advance.
You can set the alignment on the ZStack to .top. You can then also remove the Spacer.
A Spacer does nothing in a ZStack - since it's on its own layer. But setting the alignment on the ZStack will align all views to the top. If this is not what you want, you can also just put the Spacer in the inner VStack and the contents of that will all be aligned to the top also.
Code:
ZStack(alignment: .top) {
Color("background")
.edgesIgnoringSafeArea(.all)
VStack {
/* ... */
}
}
Also, to ignore the safe area at the top when applying the rounded corners, you should clip the corners and use ignoresSafeArea() within background. This ensures that you are only ignoring the safe area for the background, and not the whole view. Do the following:
.background(
Color.appColor
.cornerRadius(bottomLeft, corners: .bottomLeft)
.ignoresSafeArea()
)
// .background(Color.appColor)
// .cornerRadius(bottomLeft, corners: .bottomLeft)
.padding(.bottom, 10)
I had to remove some bits from your code as they were producing errors on my end. Working with what I had, you needed to add a Spacer() below the appropriate VStack.
Since your content was stored in a VStack embedded in another VStack, the outer VStack was essentially where the entire view lived. Putting a Spacer beneath this pushes it up to the top of the screen.
You can additionally add padding to the top of the VStack to move the view lower if you do not want it touching the top of the screen.
Code below:
import SwiftUI
struct ContentView: View {
#State var bottomLeft: CGFloat = 25
var body: some View {
ZStack {
Color("background")
.edgesIgnoringSafeArea(.all)
VStack {
VStack {
Text("Good Morning, Sarah")
.font(Font.system(size: 36))
.foregroundColor(Color.blue)
.fontWeight(.semibold)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
Text("We're glad to see you and hope you're doing well. Let's take on the day.")
.font(Font.system(size: 20))
.foregroundColor(Color.blue)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.padding(.bottom)
}
.background(Color.green)
.cornerRadius(bottomLeft)
.padding(.bottom, 10)
Spacer() //Added a spacer here
}
}
}
}

Making Button span across VStack

I currently have the following SwiftUI view:
HStack {
...
VStack {
TextField { ... }
SecureField { ... }
Button { ... }
}
...
}
I've added a .background(Color.green) to the Button, and as you can see, the view is very snug to the text.
I'm wondering if there's a way to adjust the width of the button so that it fills across VStack - something like a .fill mode for UIStackView.
The best way to do this is via .frame(maxWidth: .infinity)
https://developer.apple.com/documentation/swiftui/view-layout
If you want the button not to be centered you need to specify alignment.
e.g.: .frame(maxWidth: .infinity, alignment: .leading)
Button(action: handleSignInAction) {
Text("Sign In")
}
.frame(maxWidth: .infinity)
.background(Color.green)
Old answer from 2019:
You could use a HStack with a Text and Spacer to get a Button that fills the width of its parent:
Button(action: handleSignInAction) {
HStack {
Spacer()
Text("Sign In")
Spacer()
}
}.background(Color.green)
#d.felber's answer is almost complete, but you'd need a Spacer() on each side to center:
Button(action: {
// TODO: ...
}) {
HStack {
Spacer()
Text("Sign In")
Spacer()
}
}
.frame(maxWidth: .infinity)
Did the trick for me.
If you would like to stick to the method SwiftUI docs suggest you need to use GeometryReader and set the buttons width manually. Geometry reader updates its properties for different devices and upon rotation.
GeometryReader { geometry in
Button().frame(width: geometry.size.width, height: 100)
}
Use frame(maxWidth: .infinity) inside the Button like this:
Button(action: {...}) {
Text("Sign In")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.tint(.green)
Not like this, because the tappable area doesn't stretch:
Button(action: {}) {
Text("Sign In")
}
.frame(maxWidth: .infinity)
.background(Color.green)
Make the button text's frame the size of the UIScreen and then set the background color after it (make sure all style changes are done after changing the frame size, otherwise the style changes will only be visible on the original default frame). The frame size will propagate upward to increase the width of the button to the width of the screen as well.:
Button(action: {
// Sign in stuff
}) {
Text("Sign In")
.frame(width: UIScreen.main.bounds.width, height: nil, alignment: .center)
.background(Color.green)
}
You can also add some negative horizontal padding in between setting the frame and background in order to offset from the edge of the screen:
Button(action: {
// Sign in stuff
}) {
Text("Sign In")
.frame(width: UIScreen.main.bounds.width, height: nil, alignment: .center)
.padding(.horizontal, -10.0)
.background(Color.green)
}
Something like this?
Button(action: {
// Do your login thing here
}) {
Capsule()
.frame(height: 44)
.overlay(Text("Login").foregroundColor(Color.white)).padding()
}
I am not sure if there is a .fill method similar to UIStackView but, if what you want to do is provide some spacing on the Button (or any view for that matter) what worked for me is either setting the frame or padding
.frame(width: 300, alignment: .center) (we can also set a height here but, if not it should be able to infer the height based on the button text.
If you don't want to set an arbitrary width, you can also import UIKit and make use of UIScreen and get the devices full width. (There may be a SwiftUI way of getting this but, haven't found it at this time yet)
.frame(width: UIScreen.main.bounds.width, alignment: .center)
and then you can add a little bit of padding for some breathing room
.padding(.all, 20)
The issue with the padding is that it will add onto the additional width of the screen so we would have to take into account when setting the width.
(20 * 2 sides from leading and trailing)
.frame(width: UIScreen.main.bounds.width - 40, alignment: .center)
(breathing room is for when the text covers to the end of the screen or if your alignment is .leading or .trailing)