
SwiftUI For Dummies
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
Have a unique app idea but worried you don't quite have the coding skills to build it? Good news: You can stop fretting about someone beating you to market with the same idea and start work right now using SwiftUI. SwiftUI is a gateway app development framework that has become one of the best ways for fledgling developers to get iOS apps off the ground without having to become a coding expert overnight.
SwiftUI For Dummies makes that process even faster, providing a friendly introduction to the SwiftUI and Swift programming language and helping you feel right at home creating and building with playgrounds. The book also covers the frameworks and APIs that make it so easy to create smooth, intuitive interfaces--just dive right in and have fun!
* Combine projects into workspaces
* Employ Xcode editing tools
* Use constants and variables
* Test your code on iOS Simulator
Time is of the essence, and with SwiftUI For Dummies, it's also on your side. Get going with this friendly guide today, and you'll be celebrating the successful launch of your app way before you thought possible!
More details
Other editions
Additional editions

Person
Content
- Intro
- Title Page
- Copyright Page
- Table of Contents
- Introduction
- About This Book
- Foolish Assumptions
- Icons Used in This Book
- Beyond the Book
- Where to Go from Here
- Part 1 Getting Started with Swift and SwiftUI
- Chapter 1 Introducing SwiftUI
- Understanding What SwiftUI Is
- Getting the Tools
- Hello, SwiftUI
- Automatically previewing your user interface using the canvas
- Working with Live Preview
- Generating different previews
- The Gory Details
- Info.plist
- AppDelegate.swift
- SceneDelegate.swift
- Chapter 2 Basics of the Swift Programming Language
- Basic Swift Syntax
- Constants
- Variables
- Strings
- Comments
- Basic Data Types
- Integers
- Floating-point numbers
- Booleans
- Tuples
- Arrays
- Retrieving elements from an array
- Inserting elements into an array
- Modifying elements in an array
- Appending elements to an array
- Removing elements from an array
- Dictionaries
- Retrieving elements from a dictionary
- Modifying an item in a dictionary
- Removing an item from a dictionary
- Optional Types
- Working with implicitly unwrapped optionals
- Using optional binding
- Unwrapping optionals using "?"
- Using the nil coalescing operator
- Functions
- Understanding input parameters
- Returning a value
- Flow Control
- If-Else statement
- Ternary conditional operator
- Switch statement
- Looping
- For-In loop
- While loop
- Repeat-While loop
- Control transfer statements
- Range operators
- Structures
- Memberwise initializers
- Structures as value types
- Classes
- Defining a class
- Understanding properties
- Using methods in classes
- Trying out the self property
- Closures
- Understanding closures
- Using functions as closures
- Assigning closures to variables
- Writing closures inline
- Understanding type inference
- Using shorthand argument names
- Working with the operator function
- Using trailing closures
- Protocols
- Defining and using a protocol
- Conforming to a protocol
- Using the Codable protocol
- Using the some keyword
- Part 2 Understanding the Basics of SwiftUI
- Chapter 3 Getting Started with the Basics of SwiftUI
- Taking a Look at SwiftUI Views
- Conforming to the View protocol
- Using modifiers
- Stacking modifiers
- Using the Inspector
- Displaying an Image
- Using modifiers on the Image view
- Resizing images
- Displaying a Button
- Customizing the button
- Adding actions
- Stacking the Views
- VStack
- HStack
- Putting on the Finishing Touches
- Chapter 4 Handling User Inputs and Custom Views
- Looking at Input Views
- TextField
- SecureField
- Toggle
- Slider
- Stepper
- Picker
- Composing Custom Views
- Composing the custom view
- Using the custom view
- Chapter 5 Displaying Lists of Items
- Using the List View to Display Items
- Customizing the rows
- Adding rows programmatically
- Alternative way to generate rows in a List view
- Displaying the List within a NavigationView
- Making the items tappable
- Adding rows
- Using the Identifiable protocol
- Deleting rows
- Editing rows
- Moving rows
- Displaying Sections
- Displaying sections from a dictionary
- Changing the style of the List view
- Previewing in Light and Dark Modes
- During runtime
- During design time
- Chapter 6 Creating Navigation and Tabbed Applications
- Creating Navigation Apps
- Working with the two key views in navigation-style apps
- Navigating to a page
- Navigating programmatically
- Creating a news reader application
- Creating Tabbed Applications
- Using the TabView
- Selecting TabViews programmatically
- Chapter 7 Formatting Your User Interface
- Laying Out Views Using Stacks
- VStack
- HStack
- ZStack
- Using Container Views
- Form and Section
- Group
- Divider
- Part 3 Exploring with SwiftUI in More Detail
- Chapter 8 Understanding State Management in SwiftUI
- Using a Property Wrapper
- Maintaining State Using State Variables
- Binding State Variables
- Managing State from External Objects
- Using the ObservableObject protocol and @Published
- Using the @ObservedObject
- Sharing Objects
- Accessing Built-in Environment Variables
- Defining your own environment keys
- Using your own environment keys
- Chapter 9 Using Legacy UIKit Views and View Controllers in SwiftUI
- Using UIKit in SwiftUI
- Understanding the UIKit View Controller life cycle
- Understanding the SwiftUI view life cycle
- Using the UIViewRepresentable Protocol for UIKit Views
- ActivityIndicator
- WebView
- Using the UIViewControllerRepresentable Protocol for UIKit View Controllers
- Creating the ImagePickerViewController
- Handling events using coordinators
- Defining the methods in the Coordinator class
- Using the updated ImagePickerViewController
- Part 4 Performing Animations and Drawings
- Chapter 10 Drawings and Special Effects
- Drawing Using the Five Built-in Shapes
- Rectangles
- Rounded rectangles
- Circles
- Capsules
- Ellipses
- Clipping with the Basic Shapes
- Drawing Custom Shapes
- Drawing lines
- Filling the shape
- Drawing a border
- Drawing an arc
- Combining fill and stroke
- Using Special Effects in SwiftUI
- Blend modes
- Blurs
- Saturation
- Chapter 11 Performing Animations in SwiftUI
- Understanding How to Animate
- Specifying the type of animation
- Repeating the animation
- Stopping the animation
- Performing Your Own Animation
- Rotating in 2D
- Rotating in 3D
- Creating a Custom Progress Indicator
- Indeterminate progress indicator
- Determinate progress indicator
- Chapter 12 Creating a Complete Project
- Understanding What the App Does
- Building the Project
- Creating the layouts
- Defining the news sources and observable objects
- Fetching the data
- Displaying the news headlines
- Displaying the images
- Displaying the news
- Creating the share sheet
- Creating the preferences view
- Persisting the user's preferences
- Deploying the App
- Part 5 The Part of Tens
- Chapter 13 Ten SwiftUI Tips and Tricks
- Resuming Live Preview
- Implementing Localization
- Combining Text Views
- Creating Custom Modifiers
- Displaying Multiple Alerts
- Enabling Debug Preview
- Previewing Using Different Devices
- Dark Mode Only Works On NavigationView
- Extracting Subviews
- Displaying a Context Menu
- Chapter 14 Ten Great SwiftUI Resources
- Apple
- SwiftUI by Example
- 100 Days of SwiftUI
- Gosh Darn SwiftUI
- SwiftUI Hub
- Awesome SwiftUI
- raywenderlich.com
- Swift Talk
- About SwiftUI
- Stack Overflow
- Appendix: Code Snippets for Common SwiftUI Views
- Index
- EULA
Chapter 1
Introducing SwiftUI
IN THIS CHAPTER
Understanding what SwiftUI is
Getting the tools for SwiftUI
Comparing UIKit to SwiftUI
Using the preview canvas and Live Preview
Understanding the various files in a SwiftUI project
I know the feeling of being on the verge of learning something new. If you're anything like me, you're eager to try things out and see how it feels. And that's exactly what you do in this chapter!
In this chapter, I explain what SwiftUI is, show you how SwiftUI has changed the user interface (UI) development paradigm, and explain how SwiftUI makes the process easier going forward. Then I tell you how you can get started with the necessary tools. Finally, with the tools that you've installed, you create your first iOS application using SwiftUI, and learn how the various components in your project work together as a whole.
Understanding What SwiftUI Is
SwiftUI is a declarative programming framework for developing UIs for iOS, iPadOS, watchOS, tvOS, and macOS applications. In fact, SwiftUI was invented by the watchOS group at Apple.
Before SwiftUI was introduced, most developers used UIKit and Storyboard (which is still supported by Apple in the current version of Xcode, as of this writing [version 11.4.1]) to design a UI. Using UIKit and Storyboard, developers drag and drop View controls onto View Controllers and connect them to outlets and actions on the View Controller classes. This model of building UIs is known as Model View Controller (MVC), which creates a clean separation between UI and business logic.
The following shows a simple implementation in UIKit and Storyboard. Here, a Button and Label view have been added to the View Controller in Storyboard; two outlets and an action have been created to connect to them:
class ViewController: UIViewController {
@IBOutlet weak var lbl: UILabel!
@IBOutlet weak var button: UIButton!
@IBAction func btnClicked(_ sender: Any) {
lbl.text = "Button tapped"
}
For laying out the views, you use auto-layout to position the button and label in the middle of the screen (both horizontally and vertically).
To customize the look and feel of the button, you can code it in the loadView() method, like this:
override func loadView() {
super.loadView()
// background color
button.backgroundColor = UIColor.yellow
// button text and color
button.setTitle("Submit", for: .normal)
button.setTitleColor(.black, for: .normal)
// padding
button.contentEdgeInsets = UIEdgeInsets(
top: 10, left: 10, bottom: 10, right: 10)
// border
button.layer.borderColor =
UIColor.darkGray.cgColor
button.layer.borderWidth = 3.0
// text font
button.titleLabel!.font =
UIFont.systemFont(ofSize: 26, weight:
UIFont.Weight.regular)
// rounder corners
button.layer.cornerRadius = 10
// auto adjust button size
button.sizeToFit()
}
Figure 1-1 shows the button that has customized. UIKit is an event-driven framework, where you can reference each view in your view controller, update its appearance, or handle an event through delegates when some events occurred.
FIGURE 1-1: UIKit is event driven, and it uses delegates to handle events.
In contrast, SwiftUI is a state-driven, declarative framework. In SwiftUI, you can implement all the above with the following statements (I explain how to build all these later in this chapter):
struct ContentView: View {
@State private var label = "label"
var body: some View {
VStack {
Button(action: {
self.label = "Button tapped"
}) {
Text("Submit")
.padding(EdgeInsets(
top: 10, leading: 10,
bottom: 10, trailing: 10))
.background(Color.yellow)
.foregroundColor(Color.black)
.border(Color.gray, width: 3)
.font(Font.system(size: 26.0))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray,
lineWidth: 5)
)
}
Text(label)
.padding()
}
}
}
Notice that all the views are now created declaratively using code - no more drag-and-drop in Storyboard. Layouts are now also specified declaratively using code (the VStack in this example stacks all the views vertically). Delegates are now replaced with closures. More important, views are now a function of state (and not a sequence of events) - the text displayed by the Text view is now bound to the state variable label. When the button is tapped, you change the value of the label state variable, which automatically updates the text displayed in the Text view. This programming paradigm is known as reactive programming.
Figure 1-2 shows the various views in action.
FIGURE 1-2: SwiftUI is a state-driven declarative framework.
Getting the Tools
To start developing using SwiftUI, you need the following:
- Xcode version 11 or later
- A deployment target (Simulator or real device) of iOS 13 or later
- macOS Mojave (10.14) or later (Note that if you're running macOS Mojave, you won't be able to use Live Preview and design canvas features; full features are available only in macOS Catalina (10.15) and later.)
To install Xcode, you can install it from the App Store on your Mac (see Figure 1-3).
Alternatively, if you have a paid Apple developer account (you need this if you want to make your apps available on the App Store, but this is not a requirement for trying out the examples in this book), head over to https://developer.apple.com, sign in, and download Xcode directly.
FIGURE 1-3: Installing Xcode from the Mac App Store.
For this book, our focus is on developing iOS applications for the iPhone. Developing iPad, watchOS, tvOS, and macOS applications using SwiftUI is beyond the scope of this book.
Hello, SwiftUI
After you've installed Xcode, you'll probably be very eager to try out SwiftUI. So, let's take a dive into SwiftUI and see how it works! Follow these steps:
- Launch Xcode.
- Click Create a new Xcode project (see Figure 1-4).
- Select Single View App and click Next (see Figure 1-5).
- In the Product Name field, enter HelloSwiftUI (see Figure 1-6).
- In the Organization Name field, enter your name.
- In the Organization Identifier field, enter a unique identifier, such as the reverse domain name of your company.
- From the User Interface drop-down list, select SwiftUI.
-
Click Next and save the project to a location on your Mac.
You should see the project created for you (see Figure 1-7). The
ContentView.swiftfile contains the UI for your application's main screen.
FIGURE 1-4: Launching Xcode.
FIGURE 1-5: Selecting the Single View App project type.
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.