SwiftUI text-alignment - ios

Among the many properties of the Text view, I couldn't find any related to text alignment. I've seen in a demo that it automatically handles RTL, and when placing stuff using View's body, it always centers it automatically.
Is there some concept that I'm missing about layout system in SwiftUI and if not, how can I set the text alignment properties to the Text?

You can do this via the modifier .multilineTextAlignment(.center).
Text("CENTER")
.multilineTextAlignment(.center)
Apple Documentation

From SwiftUI beta 3 forward, you can center a text view with the frame modifier:
Text("Centered")
.frame(maxWidth: .infinity, alignment: .center)

Was trying to understand this myself as other answers here mention Text.multilineTextAlignment(_:) / VStack(alignment:) / frame(width:alignment:) but each solution solves a specific problem. Eventually it depends on the UI requirement and a combination of these.
VStack(alignment:)
The alignment here is for the inner views in respective to one another.
So specifying .leading would associate all inner views to have their leading aligned with one another.
VStack(alignment: .leading, spacing: 6) {
Text("Lorem ipsum dolor")
.background(Color.gray.opacity(0.2))
Text("sit amet")
.background(Color.gray.opacity(0.2))
}
.background(Color.gray.opacity(0.1))
.frame
In frame(width:alignment:) or frame(maxWidth:alignment:), the alignment is for the contents within the given width.
VStack(alignment: .leading, spacing: 6) {
Text("Lorem ipsum dolor")
.background(Color.gray.opacity(0.2))
Text("sit amet")
.background(Color.gray.opacity(0.2))
}
.frame(width: 380, alignment: .trailing)
.background(Color.gray.opacity(0.1))
The inners views are leading aligned respective to one another but the views themselves are trailing aligned respective to the VStack.
.multilineTextAlignment
This specifies the alignment of the text inside and can be seen best when there are multiple lines otherwise without a defined frame(width:alignment), the width is automatically adjusted and gets affected by the default alignments.
VStack(alignment: .trailing, spacing: 6) {
Text("0. automatic frame\n+ view at parent's specified alignment\n+ multilineTA not set by default at leading")
.background(Color.gray.opacity(0.2))
Text("1. automatic frame\n+ view at parent's specified alignment\n+ multilineTA set to center")
.multilineTextAlignment(.center)
.background(Color.gray.opacity(0.2))
Text("2. automatic frame\n+ view at parent's specified alignment\n+ multilineTA set to trailing")
.multilineTextAlignment(.trailing)
.background(Color.gray.opacity(0.2))
}
.frame(width: 380, alignment: .trailing)
.background(Color.gray.opacity(0.1))
Tests with combinations:
VStack(alignment: .trailing, spacing: 6) {
Text("1. automatic frame, at parent's alignment")
.background(Color.gray.opacity(0.2))
Text("2. given full width & leading alignment\n+ multilineTA at default leading")
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.gray.opacity(0.2))
Text("3. given full width & center alignment\n+ multilineTA at default leading")
.frame(maxWidth: .infinity, alignment: .center)
.background(Color.gray.opacity(0.2))
Text("4. given full width & center alignment\n+ multilineTA set to center")
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity, alignment: .center)
.background(Color.gray.opacity(0.2))
Text("5. given full width & center alignment\n+ multilineTA set to trailing")
.multilineTextAlignment(.trailing)
.frame(maxWidth: .infinity, alignment: .center)
.background(Color.gray.opacity(0.2))
Text("6. given full width but no alignment\n+ multilineTA at default leading\n+ leading is based on content, looks odd sometimes as seen here")
.frame(maxWidth: .infinity)
.background(Color.gray.opacity(0.2))
}
.frame(width: 380)
.background(Color.gray.opacity(0.1))

I've actually run into the problem where I had to align text on a single line. What I've found to work is this:
Text("some text")
.frame(alignment: .leading)
If you combine this with the frame width parameter you can get some nice text block formatting for labels and such.

I guess SwiftUI wants us to use wrappers like stacks for such things.
So instead of writing something like Text("Hello World").aligned(.leading), the following is encouraged:
VStack(alignment: .leading) {
Text("Hello World")
}

We need to align the Text and not the Stack it's in. So calling multilineTextAlignment(.center) and setting the line limits I can be able to see the texts aligned to center. I don't know why I have to set the line limits, I thought it would expand if you have a large text.
Text("blahblah")
.font(.headline)
.multilineTextAlignment(.center)
.lineLimit(50)

If you would like to keep constant width for the Text, the ".multilineTextAlignment(.leading)" won't take any effect until there is only one line of text.
This is the solution that worked for me:
struct LeftAligned: ViewModifier {
func body(content: Content) -> some View {
HStack {
content
Spacer()
}
}
}
extension View {
func leftAligned() -> some View {
return self.modifier(LeftAligned())
}
}
Usage:
Text("Hello").leftAligned().frame(width: 300)

I had the same problem.
i used this for fixing that.
Text("Test")
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)

You can set alignment for Vertical stackView as leading. Like below
VStack(alignment: .leading) {
Text("Turtle Rock")
.font(.title)
Text("Joshua Tree National Park")
.font(.subheadline)
}

I'd like to use Spacer() view to aligning text block.
This example show text at the trailing side:
HStack{
Spacer()
Text("Wishlist")
}

You can always add a frame to the Text field and can modify it's alignment.
Text("Hello World!")
.frame(alignment : .topLeading)
Since, this is just for a couple of lines - this is better than using alignment on either of the Stacks

Not sure if this is the answer you are looking for but I have experienced that SwiftUI automatically switches to RTL for languages like Arabic, you don't need to explicitly specify that like in UIKit.

You can use this property of SwiftUI
multilineTextAlignment
for TextAlignment.
VStack {
Text("Your Text")
.multilineTextAlignment(.center)
}

Related

SwiftUI - can I make one element in Form fill the whole screen width (without horizontal margins)?

I would like a single item inside SwiftUI Form to run from side to side, without having Form's default margins.
Unfortunately, whatever I do (like ading a wider .frame, negative horizontal padding, or .offset), the team image view seems to be always cropped by the form to fit the form area (= has horizontal margins).
Is it possible to make the Image below touch the left and right side of the screen?
I am using Form for my app settings, but I would like to add a full-width section there (think eg. a banner to promote a feature).
SwiftUI Playgrounds code:
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
Form {
Section(
header: Text("First section")
) {
Text("Hello world")
}
Text("The image below should be stretched to touch the left and right window edge, without being cropped by the Form.")
Image(systemName: "sun.max.fill")
.resizable()
.aspectRatio(contentMode: .fill)
.listRowInsets(EdgeInsets()) // this is supposed to fix the problem, but all it does is to set the default item inner padding to zero, so the image at least touches the edge of teal area.
.listRowBackground(Color.teal)
Section(
header: Text("Last section")
) {
Text("Hello world")
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
How it looks:
Unfortunately, SwiftUI Form is very temperamental and forces you to strictly adhere to the standard iOS Settings screen formatting.
Fortunately, you can re-implement similar formatting yourself with SwiftUI!
For the top, something like:
VStack(spacing: 4) {
Text("FIRST SECTION")
.font(.system(size: 12, weight: .regular))
.foregroundColor(.gray)
.padding(.leading)
Text("Hello, world!")
.font(.system(size: 15, weight: .regular))
.foregroundColor(.black)
.padding(.horizontal)
.frame(height: 44, alignment: .center)
.background(Color.white)
.cornerRadius(10)
}

SwiftUI: How to know correct order of modifiers?

I'm pretty new to SwiftUI, learning it for the first time, and couldn’t understand why the below snippet doesn’t work. Ideally, the VStack should stretch in all directions and the Image should have a width of 200px without losing its aspect ratio.
Code
struct ContentView: View {
var body: some View {
VStack() {
Image("Image Name")
.resizable()
.frame(width: 200)
.aspectRatio(contentMode: .fit)
}
.background(Color.red)
.frame(maxWidth: .infinity,maxHeight: .infinity)
}
}
After I accidentally reordered the modifiers, it worked. So, how am I supposed to know the correct order of modifiers without a hit and trial method each time?
// new VStack modifier order
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
// new Image modifier order
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 200)
The best way to think about it for now is to imagine that SwiftUI renders your view after every single modifier. So, as soon as you say .background(Color.red) it colors the background in red, regardless of what frame you give it. If you then later expand the frame, it won’t magically redraw the background – that was already applied.
Of course, this isn’t actually how SwiftUI works, because if it did it would be a performance nightmare, but it’s a neat mental shortcut to use while you’re learning.
Please refer to this link for more details https://www.hackingwithswift.com/books/ios-swiftui/why-modifier-order-matters#:~:text=Every%20time%20we%20modify%20a,up%3A%20ModifiedContent%3CModifiedContent%3C%E2%80%A6

How to limit width of Text in SwiftUI

I was trying to make a speech bubble like so:
Text("Hello my name is Johnny Miller and I am new here")
.foregroundColor(.white)
.padding()
.background(.blue)
.cornerRadius(25)
However I thought the speech bubble looked way wider than it needed to be. Therefore I tried to limit how far out the bubble can stretch before it goes to a new line. The easiest way which came to mind was this:
Text("Hello my name is Johnny Miller and I am new here")
.foregroundColor(.white)
.padding()
.background(.blue)
.cornerRadius(25)
.frame(maxWidth: 300) // << Limits how wide it can stretch
This worked for long messages but when the text was small such as "Hello," the frame would stay at 300pts and refused to resize to its ideal width.
I tried using .fixedSize() but this would cause truncation when the text was long.
I couldn't find a way to cap the width of the text and still have it be its ideal size. If someone could propose a solution I would be extremely grateful.
In short: The text frame should never cross 300pts in width but it can be as tall as it wants.
Thanks in advance!
Edit
These are the things I've tried so far:
Text("Hello")
.foregroundColor(.white)
.padding()
.background(.blue)
.cornerRadius(25)
.frame(maxWidth: 300)
.lineLimit(nil)
which causes the "Hello" bubble to have a frame of 300 (I've provided an image above)
and I've tried:
Text("Hello my name is Johnny Miller and I am new here")
.foregroundColor(.white)
.padding()
.background(.blue)
.cornerRadius(25)
.frame(maxWidth: 300)
.lineLimit(nil)
.fixedSize()
which gave me:

Add horizontal padding to TextEditor but prevent it from shifting scrollbar inside as a result

I'm using a TextEditor that I'd like to include horizontal padding for, so that the text doesn't stick to either edge. However, the problem is if I include it, and the text within is scrollable, then the scrollbar is not positioned to the far-right, but has instead been moved inside by the padding amount.
TextEditor(text: $text)
.background(Color.white)
.foregroundColor(Color.black)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.customFont(.body)
.lineSpacing(8)
.padding(.leading)
.padding(.trailing)
You added padding to external frame, but need to indent internal text container. The possible solution (as TextEditor is actually UITextView) to use appearance. So the solution would be to add the following in parent view of TextEditor
init() {
UITextView.appearance().textContainerInset =
UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12) // << !!
}
// ... other code
TextEditor(text: $text)
.background(Color.white)
.foregroundColor(Color.black)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.customFont(.body)
.lineSpacing(8)
Tested with Xcode 12 / iOS 14

Get width of Text in SwiftUI

how can I get the width of a Text component?
I want to make my Button that is under the Text, the same width as the Text itself.
VStack(alignment: .center, spacing: 20) {
Text("Finde heraus, was gerade in der Welt los ist.")
.font(.largeTitle).bold().lineLimit(3).multilineTextAlignment(.leading)
Button(action: {
}, label: {
Text("Account erstellen").bold()
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: 40).padding(.top, 0)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(20)
})
}.padding([.leading, .trailing], 25)
Which is giving me this result, its pretty ugly in my opinion:
On the iPad the width between the text and the button is even bigger
How can I solve this issue.
Thanks In advance.
It seems there is a bug in the bold() attribute. Removing it caused the text to align as you are expecting. You can try filing a bug, or wait it out and see if it gets fixed over the course of the beta period.
Text("Finde heraus, was gerade in der Welt los ist.")
.font(.largeTitle)
.lineLimit(3)
.multilineTextAlignment(.leading)

Resources