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

Applying groups of styles using ViewModifier

SwiftUI comes with built-in modifiers such as background() and fontWeight(), among others. It also gives you the ability to create your own custom modifiers. You can use custom modifiers to combine multiple existing modifiers into one.

In this section, we will create a custom modifier that adds rounded corners and a background to a Text view.

Getting ready

Create a new SwiftUI project named UsingViewModifiers.

How to do it…

Let’s create a view modifier and use a single line of code to apply it to a Text view. The steps are given here:

  1. Replace the current body of the ContentView view with:
    Text("Perfect")
    
  2. At the end of the ContentView.swift file, create a struct that conforms to the ViewModifier protocol, accepts a parameter of type Color, and applies styles to the view’s body:
    struct BackgroundStyle: ViewModifier {
        var bgColor: Color
        func body(content: Content) -> some View{
            content
            .frame(width:UIScreen.main.bounds.width * 0.3)
            .foregroundStyle(.black)
            .padding()
            .background(bgColor)
            .cornerRadius(20)
        }
    }
    
  3. Add a custom style to the text using the modifier() modifier:
    Text("Perfect").modifier(BackgroundStyle(bgColor:
         .blue))
    
  4. To apply styles without using a modifier, create an extension to the View protocol. The extension should be created outside the struct or Xcode will issue an error:
    extension View {
        func backgroundStyle(color: Color) -> some View{
            self.modifier(BackgroundStyle(bgColor: color))
        }
    }
    
  5. Replace the modifier on the Text view with the backgroundStyle() modifier that you just created, which will add your custom styles:
        Text("Perfect")
            .backgroundStyle(color: Color.red)
    
  6. The result should look like this:

Figure 1.15: Custom view modifier

This concludes the section on view modifiers. View modifiers promote clean coding and reduce repetition.

How it works…

A view modifier creates a new view by altering the original view to which it is applied. We create a new view modifier by creating a struct that conforms to the ViewModifier protocol and apply our styles in the implementation of the required body function. You can make the ViewModifier customizable by requiring input parameters/properties that would be used when applying styles.

In the example here, the bgColor property is used in our BackGroundStyle struct, which alters the background color of the content passed to the body function.

At the end of Step 2, we have a functioning ViewModifier but decide to make it easier to use by creating a View extension and adding in a function that calls our struct:

extension View {
    func backgroundStyle(color: Color) -> some View {
        modifier(BackgroundStyle(bgColor: color))
    }
}

We are thus able to use .backgroundStyle(color: Color) directly on our views instead of .modifier(BackgroundStyle(bgColor:Color)).

See also

Apple documentation on view modifiers: https://developer.apple.com/documentation/swiftui/viewmodifier.

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