NEW: Learn SwiftUI with my free YouTube video series! >>

< What’s in the basic template?   How to style text views with fonts, colors, line spacing, and more >

How to create static labels with a Text view

Text views show static text on the screen, and are equivalent to UILabel in UIKit. At their most basic they look like this:

Text("Hello World")

Inside the preview window for your content view you’re likely to see “Automatic preview updating paused” – go ahead and press Resume to have Swift start building your code and show you a live preview of how it looks.

By default text views wrap across as many lines as they need, but if you’d rather limit the number of lines they can use you should add the lineLimit modifier, like this:

Text("Hello World")
    .lineLimit(3)

Tip: Notice the way lineLimit(3) is placed below and to the right of Text("Hello World"). This is not required, but it does make your code easier to read in the long term.

If you place a line limit on some text then provide it with a string that’s too long to fit in the available space, SwiftUI will truncate the text so that it ends with “...”.

You can adjust the way SwiftUI truncates your text: the default is to remove text from the end and show an ellipsis there instead, but you can also place the ellipsis in the middle or beginning depending on how important the various parts of your string are.

For example, this truncates your text in the middle:

var body: some View {
    Text("This is an extremely long textbstring that will never fit even the widest of Phones")
        .lineLimit(1)
        .truncationMode(.middle)
}

Regardless of how you truncate the text, what you’ll see is that your text view sits neatly centered in the main view. This is the default behavior of SwiftUI – unless it’s told to position views somewhere else, it positions them relative to the center of the screen.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< What’s in the basic template?   How to style text views with fonts, colors, line spacing, and more >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.4/5

Click here to visit the Hacking with Swift store >>