`SwiftUI` Framework Learning and Usage Guide. 🚀

Overview

Build Status Swift Xcode Xcode MIT

This article refers to SwiftUI apple example and records the results of the exploration here, I hope to be helpful to you.

For the content described in this article, by default you have some experience based on Swift language development, so it will not describe every detail in detail; if you have doubts about Swift syntax, you can learn Swift Grammar.

When learning and using SwiftUI, if you have any questions, you can join the SwiftUI QQ Group: 18552966 to discuss communication.

中文版 🇨🇳

⭐️ Stargazers over time

Stargazers over time

💻 Requirements

  • macOS 15
  • Xcode 11.0
  • iOS 13.0

Directory:

Basic View

Layout

State and Data Flow

Gestures

Basic View

Text

Text is used to display one or more lines of text content with the same effect as UILabel, but it is even better.

If you want to create Text, just create it with Text("SwiftUI"); With chained syntax, you can also add multiple attributes to the text, such as fonts, colors, shadows, spacing between top left and right, and so on.

Example:

Text("SwiftUI")
    .foregroundColor(.orange)
    .bold()
    .font(.system(.largeTitle))
    .fontWeight(.medium)
    .italic()
    .shadow(color: .black, radius: 1, x: 0, y: 2)
View running results

HStack and VStack controls are used to host multiple views, as mentioned later.

🔝

TextField

TextField is used to add a normal input box, which is often used as a text input.

Example:

TextField(self.$name, placeholder: self.nameText, onEditingChanged: { changed in
    print("onEditing: \(changed)")
}) {
    print("userName: \(self.name)")
    self.endEditing(true)
}}
.padding(10)
.frame(height: 50)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
View running results

🔝

SecureField

SecureField is generally used as a password input. It is used in the same way as TextField. The example and the running effect are the same as TextField.

Image

The Image control is used to display images, example:

Image("icon")
    .resizable()
    .frame(width: 100,
           height: 100,
           alignment: .center)
View running results

🔝

WebImage

webImage is used to download the web image, use the URLSession to download the original Image after successful download; you can also use Kingfisher in the downloadWebImage function .

Example:

var body: some View {
        Image(uiImage: self.uiImage ?? placeholderImage)
            .resizable()
            .onAppear(perform: downloadWebImage)
            .frame(width: 80,
                   height: 80,
                   alignment: .center)
            .onTapGesture {
                print("Tap ")
        }
    }
View running results

🔝

Button

Button is used to respond to click events.

Example:

Button(action: {
    print("Tap")
}) {
   Text("I'm a Button")
}
View running results

🔝

PullDownButton

Waiting for release.

ItemBasedPopUpButton

Waiting for release.

NavigationButton

NavigationButtonPage is used to push to the next navigation page.

Example:

NavigationLink(destination: NavigationButtonPage()) {
            Text("NavigationButton").bold()
                .foregroundColor(.orange)
                .font(.largeTitle)
            }
    .navigationBarTitle(Text("Page"))
View running results

🔝

PresentationButton is deprecated

PresentationButton is used to pop up a page. has deprecated, please use NavigationLink

🔝

EditButton

EditButton is used to trigger the editing state, just use the navigationBarItems setting when using it.

Example:

navigationBarItems(trailing: EditButton())
View running results

🔝

PasteButton

Waiting for release.

Picker

Picker can customize the selector of the data source.

Example:

Picker(selection: $leftIndex, label: Text("Picker")) {
    ForEach(0..<leftSource.count) {
        Text(self.leftSource[$0]).tag($0)
    }
    }.frame(width: UIScreen.main.bounds.width/2)
View running results

🔝

DatePicker

DatePicker is used to select the absolute date of the control.

Example:

                DatePicker(selection: $server.date, 
                in: server.spaceDate, 
                displayedComponents: .date, label: {
                    Text("")
                })
View running results

🔝

Toggle

Toggle is used to switch the selected state, for example:

Togglele(isOn: $isOn) {
    Text("State: \(self.isOn == true ? "Open":"open")")
}.padding(20)
View running results

🔝

Slider

Slider A control for selecting values from a finite range of values, example:

Slider(value: $data.rating)
View running results

🔝

Stepper

Stepper is used to increase or decrease the value, example:

Stepper(value: $value, step: 2, onEditingChanged: { c in
    print(c)
}) {
    Text("Stepper Value: \(self.value)")
    }.padding(50)
View running results

🔝

SegmentedControl is deprecated

SegmentedControl is used for segmentation condition selection, example:

SegmentedControl(selection: $currentIndex) {
    ForEach(0..<items.count) { index in
        Text(self.items[index]).tag(index)
    }
    }.tapAction {
        print("currentIndex: \(self.currentIndex)")
}
View running results

🔝

WebView

WebView is used to display an open web page, example:

struct WebViewPage : UIViewRepresentable {
    func makeUIView(context: Context) -> WKWebView  {
        return WKWebView()
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
        let req = URLRequest(url: URL(string: "https://www.apple.com")!)
        uiView.load(req)
    }
}
View running results

🔝

UIViewController

UIViewController is used to display the UIViewController that opens UIKit in SwiftUI and opens the SwiftUI View in UIViewController.

Example:

First define:

struct ControllerPage<T: UIViewController> : UIViewControllerRepresentable {
    
    typealias UIViewControllerType = UIViewController
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ControllerPage>) -> UIViewController {
        return T()
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<ControllerPage>) {
        debugPrint("\(#function)\(type(of: T.self))")
    }
    
}

Then use this:

NavigationButton(destination: ControllerPage<UIKitController>()) {
    PageRow(title: "UIViewController",subTitle: "Open UIViewController")

}
View running results

🔝

Layout

HStack

HStack is used to arrange the subviews on a horizontal line.

Example:

HStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
View running results

🔝

VStack

VStack is used to arrange the subviews on a vertical line.

Example:

VStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
View running results

🔝

ZStack

ZStack is used to override the subview, aligned on two axes.

Example:

ZStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
View running results

🔝

List

List list container to display a list of data.

Examples:

List(0..<5) { item in
    Text("Hello World !")
}.navigationBarTitle(Text("List"), displayMode: .large)
View running results

🔝

ScrollView

ScrollView is a scroll view container.

Example:

ScrollView {
    Text("SwiftUI").padding(20)
    Divider()
    Image("icon").resizable()
        .frame(width: 300, height: 300, alignment: .center)
    Divider()
    Text("Views and ... user interface.")
    }
    .border(Color.gray.gradient, width: 1)
            .cornerRadius(10)
            .padding(10)
            .navigationBarTitle(Text("ScrollView"))
View running results

🔝

ForEach

ForEach is used to present a view based on a collection of existing data.

Example:

let data = (0..<5)
var body: some View {
    ForEach(data) { e in
        Text("Hello \(e)")
            .bold()
            .font(.system(size: 25, design: .monospaced))
            .padding(5)
}
View running results

🔝

Group

Group is used to aggregate multiple views, and the properties set on the Group will be applied to each child view.

Example:

Group {
    Text("Hello World !")
    Text("Hello World !")
    }
View running results

🔝

GroupBox

Waiting for release.

Section

Section is used to create the header/footer view content, which is generally used in conjunction with the List component.

Example:

Section(header: Text("I'm header"), footer: Text("I'm footer")) {
    ForEach(0..<3) {
        Text("Hello \($0)")
    }
}
View running results

Form

Form A container for grouping controls used for data entry, such as in settings or inspectors.

Example:

Form {
   TextField("First Name", text: $firstName)
   TextField("Last Name", text: $lastName)
}
View running results

🔝

NavigationView

NavigationView is used to create a view container that contains the top navigation bar.

Example:

NavigationView {
            Text("🧚‍♂️🧚‍♀️🧜‍♂️🧜‍♀️🧞‍♂️🧞‍♀️").blur(radius: 5)
            Text("Swifter Swifter")
            .bold()
                .foregroundColor(.orange)
                .font(.largeTitle)
        }
    .navigationBarTitle(Text("NavigationView"))
View running results

🔝

TabView

TabView is used to create a view container that contains the bottom ** TabBar**.

Example:

TabView(selection: $index) {
    ForEach(0..<imgs.count) { item in
        TabItemPage(index: item)
            .tabItem{
                Image(self.imgs[item])
                Text("\(item)")
        }
        .tag(item)
    }
}
View running results

🔝

HSplitView

Waiting for release.

VSplitView

Waiting for release.

🔝

Alert

Alert is used to display a bullet reminder that needs to be associated with a trigger event.

Example:

alert(isPresented: $showAlert, content: {
            Alert(title: Text("确定要支付这100000000美元吗?"),
                  message: Text("请谨慎操作\n一旦确认,钱款将立即转入对方账户"),
                  primaryButton: .destructive(Text("确认")) { print("转出中...") },
                  secondaryButton: .cancel())
        }).navigationBarTitle(Text("Alert"))
View running results

🔝

ActionSheet

ActionSheet is used to pop up a selection box.

Example:

ActionSheet(title: Text("Title"),
            message: Text("Message"),
            buttons:
    [.default(Text("Default"), onTrigger: {
        print("Default")
        self.showSheet = false
    }),.destructive(Text("destructive"), onTrigger: {
        print("destructive")
        self.showSheet = false
    }),.cancel({
        print("Cancel")
        self.showSheet = false
    })])

usage:

.actionSheet(isPresented: $showSheet, content: {sheet})
View running results

🔝

Modal

Modal is used to pop up a view.

Example:

Modal(Text("Modal View"),onDismiss: {
    print("View Dismiss !")
})
View running results

🔝

Popover

Popover is used to pop up a view, see the results below.

Example:

.popover(isPresented: $showPop, content: {
                ImagePage()
            })
View running results

🔝

📎 About

  • The code involved in the above example is in this repository code. It is recommended to download and run the view.
  • If you have better usage and suggestions about SwiftUI, look forward to sharing it!
  • If there are omissions and errors in the examples in this article, please create a Issue !

✉️ Contacts

email : [email protected]

微博 : @晋先森

📄 License

SwiftUI is released under the MIT license. See LICENSE for details.

Comments
  • 'String' is not convertible to 'String?'

    'String' is not convertible to 'String?'

    xcode Version 11.0 beta 2 (11M337n) 模拟器:iphone xr ios 13

    运行 PageRow(title: "WebView",subTitle: "用于展示一个打开的网页") 报错内容:'String' is not convertible to 'String?'

    我不懂swift的语法,不知道该怎么解决

    opened by iosApem 11
  • How about a Q&A?

    How about a Q&A?

    感谢分享! 现在我们已经知道了如何使用各个UI组件, 那么下一步, 如何使用SwiftUI来实现更深层次的UI功能定制? 比如:

    • 如何使TextField失去焦点?
    • 如何定制TextField的键盘样式?
    • 如何指定TextField的contentType?
    • 如何为每个页面指定键盘(textInputContextIdentifier)? 还有其他等等更多, 能否整合一个Q&A页面, 请大家解答各种这样的问题?

    Now we know how to compose view controllers by SwiftUI. But then?

    • How to 'resign first responder' for a TextField manually?
    • How to customize keyboard type of TextField?
    • How to provide contentType of TextField?
    • How to provide textInputContextIdentifier for views? And more...
    good first issue 
    opened by likeSo 3
  • viewDidLoad equivalent?

    viewDidLoad equivalent?

    Hi, Currently I am looking into TabbedView and I have a question. I was managed to create a simple app containing two tabs and now I am trying to load the data once after the tab was loaded. I tried using onAppear method but unfortunately it is called every time a tab was selected. Any ideas how to handle such logic?

    question 
    opened by Reak45 2
  • Big sur  not working

    Big sur not working

    Version

    macOS version: Big sur 11.0.1

    Xcode version: 12.2

    Description

    Describe your problem: 这下面的Demo跑不起来了 https://github.com/Jinxiansen/SwiftUI/tree/doc

    question 
    opened by huangboju 1
  • remove .DS_Store and prevent it from reappearing

    remove .DS_Store and prevent it from reappearing

    macOS’s .DS_Store files shouldn’t be in a repository. This pull removes the existing one and updates .gitignore to prevent another instance from being committed.

    opened by LucasLarson 1
  • Popover drag to dismiss seems buggy

    Popover drag to dismiss seems buggy

    Version

    macOS version: 10.15.4

    Xcode version: 11.5

    iOS version: 13.5.1

    Description

    Popover drag to dismiss seems buggy

    Describe your problem:

    Check the gif: Jun-05-2020 11-26-24

    question 
    opened by PetrGuan 1
  • SwiftUI issue

    SwiftUI issue

    Version

    macOS version: 10.15.4 Xcode version: 11.4.1

    Description

    初学者,TextField那儿按照楼主的方法全都报错了,后来我找到了这个是正确的的 TextField("User Name", text: $username, onEditingChanged: { (value) in print("onEditingChanged:\(self.name)") }) { print("onCommit:\(self.name)") }} .padding(10) .frame(height: 50) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20)) Describe your problem:

    question 
    opened by Jamxscape 1
  • 'roundedBorder' is deprecated: Use `RoundedBorderTextFieldStyle` directly instead.

    'roundedBorder' is deprecated: Use `RoundedBorderTextFieldStyle` directly instead.

    Version

    macOS version: 10.15

    Xcode version: 11.0 beta 6

    Description

    Describe your problem:

    Seems that using this line for TextField .textFieldStyle(.roundedBorder) is now deprecated. The correct way should be .textFieldStyle(RoundedBorderTextFieldStyle())

    So now the new example should be:

    TextField(self.$name, placeholder: self.nameText, onEditingChanged: { changed in
        print("onEditing: \(changed)")
    }) {
        print("userName: \(self.name)")
        self.endEditing(true)
    }}
    .padding(10)
    .frame(height: 50)
    .textFieldStyle(RoundedBorderTextFieldStyle())
    .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
    
    question 
    opened by uguizu 1
Owner
晋先森
Computer Engineer, passionate about Computer Science, specially about Natural Language Processing and Machine Learning. Free Software fan.
晋先森
Powerful autolayout framework, that can manage UIView(NSView), CALayer and not rendered views. Not Apple Autolayout wrapper. Provides placeholders. Linux support.

CGLayout Powerful autolayout framework, that can manage UIView(NSView), CALayer and not rendered views. Has cross-hierarchy coordinate space. Implemen

Koryttsev Denis 45 Jun 28, 2022
MyLayout is a simple and easy objective-c framework for iOS view layout

MyLayout is a powerful iOS UI framework implemented by Objective-C. It integrates the functions with Android Layout,iOS AutoLayout,SizeClass, HTML CSS float and flexbox and bootstrap. So you can use LinearLayout,RelativeLayout,FrameLayout,TableLayout,FlowLayout,FloatLayout,PathLayout,GridLayout,LayoutSizeClass to build your App 自动布局 UIView UITableView UICollectionView RTL

欧阳大哥2013 4.2k Dec 30, 2022
FlightLayout is a light weight, and easy to learn layout framework as an extension of the UIView.

FlightLayout Introduction FlightLayout is a light weight, and easy to learn layout framework as an extension of the UIView. Functionally, it lives som

Anton 23 Apr 21, 2022
What's New In SwiftUI for iOS 16 - Xcode 14 - SwiftUI 4.0

SwiftUI4 What's New In SwiftUI for iOS 16 - Xcode 14 - SwiftUI 4.0 (Work in progress....) Swift Charts Presentation Detents(Half Sheet & Small Sheets)

Sebastiao Gazolla Jr 3 Oct 23, 2022
A powerful Swift programmatic UI layout framework.

Build dynamic and beautiful user interfaces like a boss, with Swift. Neon is built around how user interfaces are naturally and intuitively designed.

Mike 4.6k Dec 26, 2022
Lightweight Swift framework for Apple's Auto-Layout

I am glad to share with you a lightweight Swift framework for Apple's Auto-Layout. It helps you write readable and compact UI code using simple API. A

null 349 Dec 20, 2022
Declarative iOS UI sugar framework built on FlexLayout

Declarative iOS UI sugar framework built on FlexLayout

당근마켓 97 Dec 9, 2022
Lightweight declarative auto-layout framework for Swift

SwiftyLayout SwiftyLayout is a framework that allows to describe layout constraints (ie NSLayoutConstraint) as a simple mathematical formula in a Swif

Hisakuni Fujimoto 15 Nov 7, 2017
A Swift binding framework

Bond, Swift Bond Update: Bond 7 has been released! Check out the migration guide to learn more about the update. Bond is a Swift binding framework tha

Declarative Hub 4.2k Dec 31, 2022
A declarative UI framework for iOS

Layout Layout is a native Swift framework for implementing iOS user interfaces using XML template files and runtime-evaluated expressions. It is inten

Nick Lockwood 2.2k Dec 23, 2022
An elegant pagination framework written in Swift.

Paginator Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation Paginato

Grigor Hakobyan 2 Dec 16, 2021
IOS-IntegratedPhotoCapture - Integrated photo capture framework use podspec

IOS-IntegratedPhotoCapture integrated photo capture framework use podspec ======

Nguyễn Thành Nam 1 Dec 30, 2021
LemonadeDeclarativeUI framework contains some new functions for UIKit

LemonadeDeclarativeUI framework contains some new functions for UIKit. This library has been developing. If you want to contribute reach me!

Özgür Elmaslı 0 Jan 2, 2022
ErrorHierarchy - A sibling framework to ActionHierarchy, but specialized for Error handling

Error Hierarchy This is a sibling framework to ActionHierarchy, but specialized

Emilio Peláez 1 Mar 27, 2022
Using the UIKitChain framework, You can create a UIKit component in one line of code.

Using the UIKitChain framework, You can create a UIKit component in one line of code. Installation CocoaPods CocoaPods is a dependency manager for Coc

Malith Nadeeshan 1 Sep 1, 2022
🐵Fooling around with Apples private framework AvatarKit

Fooling around with Apples private framework AvatarKit, the framework used in Messages.app for recording Animoji videos. If you are looking to create your own Animoji, take a look at SBSCustomAnimoji.

Simon Støvring 968 Dec 25, 2022
A Set of Tools To Extend UIKit (Classic iOS Framework)

RVS_UIKit_Toolbox A set of basic UIKit tools, for Swift iOS app development. Overview This package offers a few extensions of standard UIKit classes,

The Great Rift Valley Software Company 2 Jul 8, 2022
Expose layout margins and readable content width to SwiftUI's Views

SwiftUI Layout Guides This micro-library exposes UIKit's layout margins and readable content guides to SwiftUI. Usage Make a view fit the readable con

Thomas Grapperon 26 Dec 23, 2022
An experiment creating a particle emitter using the new TimelineView and Canvas views in SwiftUI

Particle Emitter An experiment creating a particle emitter using the new Timelin

Emilio Peláez 8 Nov 11, 2022