Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook A guide for building beautiful and interactive SwiftUI apps

Arrow left icon
Product type Paperback
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Length 798 pages
Edition 3rd Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Juan C. Catalan Juan C. Catalan
Author Profile Icon Juan C. Catalan
Juan C. Catalan
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Using the Basic SwiftUI Views and Controls FREE CHAPTER 2. Displaying Scrollable Content with Lists and Scroll Views 3. Exploring Advanced Components 4. Viewing while Building with SwiftUI Preview in Xcode 15 5. Creating New Components and Grouping Views with Container Views 6. Presenting Views Modally 7. Navigation Containers 8. Drawing with SwiftUI 9. Animating with SwiftUI 10. Driving SwiftUI with Data 11. Driving SwiftUI with Combine 12. SwiftUI Concurrency with async await 13. Handling Authentication and Firebase with SwiftUI 14. Persistence in SwiftUI with Core Data and SwiftData 15. Data Visualization with Swift Charts 16. Creating Multiplatform Apps with SwiftUI 17. SwiftUI Tips and Tricks 18. Other Books You May Enjoy
19. Index

Dealing with text

The most basic building block of any application is text, which we use to provide or request information from a user. Some text requires special treatment, such as password fields, which must be masked for privacy reasons.

In this recipe, we will implement different types of SwiftUI Text views. A Text view is used to display one or more lines of read-only text on the screen. A TextField view is used to display multiline editable text, and a SecureField view is used to request private information that should be masked, such as passwords.

Getting ready

Create a new SwiftUI project named FormattedText.

How to do it…

We’ll implement multiple types of text-related views and modifiers. Each step in this section applies minor changes to the view, so note the UI changes that occur after each step. Let’s get started:

  1. Replace the initial ContentView body variable with our own VStack. The ContentView should look like the following code:
    struct ContentView: View {
    var body: some View {
            VStack{
                Text("Hello World")
            }
        }
    }
    
  2. Add the .fontWeight(.medium) modifier to the text and observe the text weight change in the canvas preview:
    Text("Hello World")
               .fontWeight(.medium)
    
  3. Add two state variables to the ContentView.swift file: password and someText. Place the values below the ContentView struct declaration. These variables will hold the content of the user’s password and Textfield inputs:
    struct ContentView: View {
        @State private var password = "1234"
        @State private var someText = "initial text"
    var body: some View {
    ...
    }
    
  4. Now, we will start adding more views to the VStack. Each view should be added immediately after the previous one. Add SecureField and a Text view to the VStack. The Text view displays the value entered in SecureField:
    SecureField("Enter a password", text: $password)
          .padding()
    Text("password entered: \(password)")
          .italic()
    
  5. Add TextField and a Text view to display the value entered in TextField:
    TextField("Enter some text", text: $someText)
       .padding()
    Text(someText)
       .font(.largeTitle)
       .underline()
    
  6. Now, let’s add some other Text views with modifiers to the list:
    Text("Changing text color and make it bold")
             .foregroundStyle(.blue)
             .bold()
    Text("Use kerning to change space between characters in the text")
              .kerning(7)
          Text("Changing baseline offset")
              .baselineOffset(100)
          Text("Strikethrough")
               .strikethrough()
          Text("This is a multiline text implemented in
               SwiftUI. The trailing modifier was added 
               to the text. This text also implements
               multiple modifiers")
                .background(.yellow)
                .multilineTextAlignment(.trailing)
                .lineSpacing(10)
    

Now is the moment to test the app. We can choose to run the app in a simulator or click the Play button in the canvas preview, which allows for interactivity. Play with the app and enter some text in the SecureField and TextField. Text entered in the SecureField will be masked, while text in the TextField will be shown.

The resulting preview should look like this:

Figure 1.4: FormattedText preview

How it works…

Text views have several modifiers for font, spacing, and other formatting requirements. When in doubt, position the cursor on the line of code that includes the Text view, and press the Esc key to reveal a list of all available modifiers. This is shown in the following example:

Figure 1.5: Using Xcode autocomplete to view formatting options

Unlike regular Text views, TextField and SecureField require state variables to store the value entered by the user. State variables are declared using the @State keyword. SwiftUI manages the storage of properties declared by using @State and refreshes the body each time the value of the state variable changes.

Values entered by the user are stored using the process of binding. In this recipe, we have state variables bound to the SecureField and TextField input parameters. The $ symbol is used to bind a state variable to the field. Using the $ symbol ensures that the state variable’s value is changed to correspond to the value entered by the user, as shown in the following example:

  TextField("Enter some text", text: $someText) 

Binding also notifies other views of state changes and causes the views to be redrawn on state change.

The wrapped value of bound state variables, which is the underlying value referenced by the state variable, is accessed without having to use the $ symbol. This is a convenience shortcut provided by Swift, as shown in the following code snippet:

  Text(someText)

See also

Apple documentation regarding SwiftUI Text view: https://developer.apple.com/documentation/swiftui/text.

You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023
Publisher: Packt
ISBN-13: 9781805121732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime