NEW: Get your ticket for Hacking with Swift Live 2019! >>

< 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 are a single line only – if you run out of space the characters will be clipped and replaced with “...”, so if our label were longer you’d see that happen. If you want to change this behavior – if you want your text view to run over more lines, you can either do this to make it have a specific number of lines:

Text("Hello World")

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.

Alternatively, you can specify nil to the lineLimit() method, which allows it to run over as many lines as needed:

Text("Hello World")

Rather than adjusting the line limit, you can also 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 string that will never fit even the widest of Phones")

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.

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< What’s in the basic template?   How to style text views with fonts, colors, line spacing, and more >
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 >>