Wei-Meng Lee - SwiftUI For Dummies

Здесь есть возможность читать онлайн «Wei-Meng Lee - SwiftUI For Dummies» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

SwiftUI For Dummies: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «SwiftUI For Dummies»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

The simplest way to create world-class apps 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
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 
, 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!

SwiftUI For Dummies — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «SwiftUI For Dummies», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

картинка 9 Using the preview canvas and Live Preview

картинка 10 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 Buttonand Labelview 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 11UIKit is event driven and it uses delegates to handle events In - фото 11

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 VStackin 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 Textview is now bound to the state variable label. When the button is tapped, you change the value of the labelstate variable, which automatically updates the text displayed in the Textview. This programming paradigm is known as reactive programming.

Figure 1-2 shows the various views in action.

FIGURE 12SwiftUI is a statedriven declarative framework Getting the Tools - фото 12

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.

SwiftUI For Dummies - изображение 13

FIGURE 1-3:Installing Xcode from the Mac App Store.

SwiftUI For Dummies - изображение 14For 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:

1 Launch Xcode.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «SwiftUI For Dummies»

Представляем Вашему вниманию похожие книги на «SwiftUI For Dummies» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «SwiftUI For Dummies»

Обсуждение, отзывы о книге «SwiftUI For Dummies» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x