Chapter 2
Getting Started with SwiftUI and Working with Text

If you've worked with UIKit before, the Text control in SwiftUI is very similar to UILabel in UIKit. It's a view for you to display one or multiple lines of text. This Text control is non-editable but is useful for presenting read-only information on screen. For example, you want to present an on-screen message, you can use Text to implement it.

In this chapter, I'll show you how to work with Text to present information. You'll also learn how to customize the text with different colors, fonts, backgrounds and apply rotation effects.

Creating a New Project for Playing with SwiftUI

First, fire up Xcode and create a new project using the App template under the iOS category. Apple has revamped some of the project templates. If you have used the older version of Xcode before, the Single Application template is now replaced with the App template.

Choose Next to proceed to the next screen and type the name of the project. I set it to SwiftUIText but you're free to use any other name. For the organization name, you can set it to your company or organization. The organization identifier is a unique identifier of your app. Here I use com.appcoda but you should set it to your own value. If you have a website, set it to your domain in reverse domain name notation.

Figure 1. Creating a new project
Figure 1. Creating a new project

To use SwiftUI, you have to choose SwiftUI in the Interface option. The language should be set to Swift. Click Next and choose a folder to create the project.

Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas. If you can't see the design canvas, you can go up to the Xcode menu and choose Editor > Canvas to enable it. To give yourself more space for writing code, you can hide both the project navigator and the inspector (see figure 2).

By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn't render the app preview. You have to click the Resume button in order to see the preview. After you click the button, Xcode renders the preview in a simulator that you choose in the simulator selection (e.g. iPhone 13 Pro).

Figure 2. The code editor and the canvas
Figure 2. The code editor and the canvas

Displaying Simple Text

The sample code generated in ContentView already shows you how to display a single line of text. You initialize a Text object and pass to it the text (e.g. Hello World) to display like this:

Text("Hello World")

The preview canvas should display Hello World on screen. This is the basic syntax for creating a text view. You're free to change the text to whatever value you want and the canvas should show you the change instantaneously.

Figure 3. Changing the text
Figure 3. Changing the text

Changing the Font Type and Color

In SwiftUI, you can change the properties (e.g. color, font, weight) of a control by calling methods that are known as Modifiers. Let's say, you want to bold the text. You can use the modifier fontWeight and specify your preferred font weight (e.g. .bold) like this:

Text("Stay Hungry. Stay Foolish.").fontWeight(.bold)

You access the modifier by using the dot syntax. Whenever you type a dot, Xcode will show you the possible modifiers or values you can use. For example, you will see various font weight options when you type a dot in the fontWeight modifier. You can choose bold to bold the text. If you want to make it even bolder, use heavy or black.

Figure 4. Choosing your preferred font weight
Figure 4. Choosing your preferred font weight

By calling fontWeight with the value .bold, it actually returns to you a new view that has the bolded text. What is interesting in SwiftUI is that you can further chain this new view with other modifiers. Say, you want to make the bolded text a little bit bigger, you write the code like this:

Text("Stay Hungry. Stay Foolish.").fontWeight(.bold).font(.title)

Since we may chain multiple modifiers together, we usually write the code above in the following format:

Text("Stay Hungry. Stay Foolish.")
    .fontWeight(.bold)
    .font(.title)

The functionality is the same but I believe you'll find the code above more easy to read. We will continue to use this coding convention for the rest of this book.

The font modifier lets you change the font properties. In the code above, we specify the title font type in order to enlarge the text. SwiftUI comes with several built-in text styles including title, largeTitle, body, etc. If you want to further increase the font size, replace .title with .largeTitle.

Note: You can always to refer the documentation (https://developer.apple.com/documentation/swiftui/font) to find out all the supported values of the font modifier.

Figure 5. Changing the font type
Figure 5. Changing the font type

You can also use the font modifier to specify the font design. Let's say, you want the font to be rounded. You can write the font modifier like this:

.font(.system(.title, design: .rounded))

Here you specify to use the system font with title text style and rounded design. The preview canvas should immediately respond to the change and show you the rounded text.

Figure 6. Using the rounded font design
Figure 6. Using the rounded font design

Dynamic Type is a feature of iOS that automatically adjusts the font size in reference to the user's setting (Settings > Display & Brightness > Text Size). In other words, when you use text styles (e.g. .title), the font size will be varied and your app will scale the text automatically, depending on the user's preference.

To use a fixed-size font, write the code like this:

.font(.system(size: 20))

This tells the system to use a fixed font size of 20 points.

You can chain other modifiers to further customize the text. Let's change the font color. To do that, you use the foregroundColor modifier like this:

.foregroundColor(.green)

The foregroundColor modifier accepts a value of Color. Here we specify .green, which is a built-in color. You may use other built-in values like .red, .purple, etc.

Figure 7. Changing the font color
Figure 7. Changing the font color

While I prefer to customize the properties of a control by writing code, you can also use the design canvas to edit them. Hold the command key and click the text to bring up a pop-over menu. Choose Show SwiftUI Inspector and then you can edit the text/font properties. What is great is that the code will update automatically when you make changes to the font properties.

Figure 8. Using the Inspect feature to edit the properties of the text
Figure 8. Using the Inspect feature to edit the properties of the text

Working with Multiline Text

Text supports multiple lines by default, so it can display a paragraph of text without using any additional modifiers. Replace your current code with the following:

Text("Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma—which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition.")
    .fontWeight(.bold)
    .font(.title)
    .foregroundColor(.gray)

You're free to replace the paragraph of text with your own text. Just make sure it's long enough. Once you have made the change, the design canvas will render a multiline text label.

Figure 9. Display multiline text
Figure 9. Display multiline text

To center align the text, insert the multilineTextAlignment modifier after the .foreground modifier and set its value to .center like this:

.multilineTextAlignment(.center)

In some cases, you may want to limit the number of lines to a certain number. You use the lineLimit modifier to control it. Here is an example:

.lineLimit(3)

Another modifier, truncationMode specifies where to truncate the text within the text view. You can truncate at the beginning, middle, or end of the text view. By default, the system is set to use tail truncation. To modify the truncation mode of the text, you use the truncationMode modifier and set its value to .head or .middle like this:

.truncationMode(.head)

After the change, your text should look like the figure below.

Figure 10. Using the .head truncation mode
Figure 10. Using the .head truncation mode

Earlier, I mentioned that the Text control displays multiple lines by default. The reason is that the SwiftUI framework has set a default value of nil for the lineLimit modifier. You can change the value of .lineLimit to nil and see the result:

.lineLimit(nil)

Setting the Padding and Line Spacing

Normally the default line spacing is good enough for most situations. To alter the default setting, you adjust the line spacing by using the lineSpacing modifier.

.lineSpacing(10)

As you see, the text is too close to the left and right side of the edges. To give it some more space, you can use the padding modifier, which adds some extra space to each side of the text. Insert the following line of code after the lineSpacing modifier:

.padding()

Your design canvas should now look like this:

Figure 11. Setting the padding and line spacing of the text
Figure 11. Setting the padding and line spacing of the text

Rotating the Text

The SwiftUI framework provides a modifier to let you easily rotate the text. You use the rotateEffect modifier and pass the degree of rotation like this:

.rotationEffect(.degrees(45))

If you insert the above line of code after padding(), you will see the text is rotated by 45 degrees.

Figure 12. Rotate the text
Figure 12. Rotate the text

By default, the rotation happens around the center of the text view. If you want to rotate the text around a specific point (say, the top-left corner), you write the code like this:

.rotationEffect(.degrees(20), anchor: UnitPoint(x: 0, y: 0))

We pass an extra parameter anchor to specify the point of the rotation.

Figure 13. Rotate the text around the top-left of the text view
Figure 13. Rotate the text around the top-left of the text view

Not only can you rotate the text in 2D, SwiftUI provides a modifier called rotation3DEffect that allows you to create some amazing 3D effects. The modifier takes two parameters: rotation angle and the axis of the rotation. Say, you want to create a perspective text effect, you write the code like this:

.rotation3DEffect(.degrees(60), axis: (x: 1, y: 0, z: 0))

With just a line of code, you have created the Star Wars perspective text!

Figure 14. Create amazing text effect by using 3D rotation
Figure 14. Create amazing text effect by using 3D rotation

You can further insert the following line of code to create a drop shadow effect for the perspective text:

.shadow(color: .gray, radius: 2, x: 0, y: 15)

The shadow modifier will apply the shadow effect to the text. All you need to do is specify the color and radius of the shadow. Optionally, you can tell the system the position of the shadow by specifying the x and y values.

Figure 15. Applying the drop shadow effect
Figure 15. Applying the drop shadow effect

Using Custom Fonts

By default, all text is displayed using the system font. Say, you find a free font on Google Fonts (e.g. https://fonts.google.com/specimen/Nunito). How can you use a custom font in the app?

Assuming you've downloaded the font files, you should first add it to your Xcode project. You can simply drag the font files to the project navigator and insert them under the SwiftUIText folder. For this demo, I just add the regular font file (i.e. Nunito-Regular.ttf). If you need to use the bold or italic font, please add the corresponding font files.

Figure 16. Adding the font file to the project
Figure 16. Adding the font file to the project

Once you added the font, Xcode will prompt you an option dialog. Please make sure you enable Copy items if added and check the SwiftUIText target.

Figure 17. Choosing the options for adding files
Figure 17. Choosing the options for adding files

After adding the font file, you still can't use the font directly. Xcode requires developers to register the font in the project configuration. In the project navigator, select SwiftUIText and then click SwiftUIText under Targets. Choose the Info tab, which displays the project configuration.

You can right Bundle name and choose Add row. Set the key name to Fonts provided by application. Next, click the disclosure indicator to expand the entry. For item 0, set the value to Nunito-Regular.ttf, which is the font file you've just added. If you have multiple font files, you can click the + button to add another item.

Figure 18. Set the font file in the project configuration
Figure 18. Set the font file in the project configuration

Now you can go back to ContentView.swift. To use the custom font, you can replace the following line of code:

.font(.title)

With:

.font(.custom("Nunito", size: 25))

Instead of using the system font style, the code above uses .custom and specifies the preferred font name. Font names can be found in the application "Font Book". You can open Finder > Application and click Font Book to launch the app.

Figure 19. Using the custom font
Figure 19. Using the custom font

Displaying Markdown Text

Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages.

In iOS 15, SwiftUI has built-in support for rendering Markdown. If you don't know what Markdown is, it allows you to style plain text using an easy to read format. To learn more about Markdown, you can check out this guide (https://www.markdownguide.org/getting-started/).

To use Markdown for rending text, all you need to do is specify the text in Markdown. The Text view automatically renders the text for you. Here is an example:

Text("**This is how you bold a text**. *This is how you make text italic.* You can [click this link](https://www.appcoda.com) to go to appcoda.com")
    .font(.title)

If you write the code in ContentView, you will see how the given text is rendered. To test the hyperlink, you have to run the app in simulators. When you tap the link, iOS will redirect to mobile Safari and open the URL.

Figure 20. Using Markdown
Figure 20. Using Markdown

Summary

Do you enjoy creating user interfaces with SwiftUI? I hope so. The declarative syntax of SwiftUI makes the code more readable and easier to understand. As you have experienced, it only takes a few lines of code in SwiftUI to create fancy text in 3D style.

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""