Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Swift 4 Programming Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Swift 4 Programming Cookbook

Swift 4 Programming Cookbook

By : Keith Moon
4.4 (5)
close
close
Swift 4 Programming Cookbook

Swift 4 Programming Cookbook

4.4 (5)
By: Keith Moon

Overview of this book

Swift 4 is an exciting, multi-platform, general-purpose programming language. Being open source, modern and easy to use has made Swift one of the fastest growing programming languages. If you interested in exploring it, then this book is what you need. The book begins with an introduction to the basic building blocks of Swift 4, its syntax and the functionalities of Swift constructs. Then, introduces you to Apple's Xcode 9 IDE and Swift Playgrounds, which provide an ideal platform to write, execute, and debug the codes thus initiating your development process. Next, you'll learn to bundle variables into tuples, set order to your data with an array, store key-value pairs with dictionaries and you'll learn how to use the property observers. Later, explore the decision-making and control structures in Swift and learn how to handle errors in Swift 4. Then you'll, examine the advanced features of Swift, generics and operators, and then explore the functionalities outside of the standard library, provided by frameworks such as Foundation and UIKit. Also, you'll explore advanced features of Swift Playgrounds. At the end of the book, you'll learn server-side programming aspect of Swift 4 and see how to run Swift on Linux and then investigate Vapor, one of the most popular server-side frameworks for Swift.
Table of Contents (9 chapters)
close
close

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.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Swift 4 Programming Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon