# SwiftUI
**Repository Path**: aaabced/SwiftUI
## Basic Information
- **Project Name**: SwiftUI
- **Description**: SwiftUI 布局框架的一些官方示例,希望对你了解和学习这门新布局框架有所帮助
- **Primary Language**: Swift
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 68
- **Created**: 2020-12-30
- **Last Updated**: 2020-12-30
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
[](https://github.com/Jinxiansen/SwiftUI)
[](https://swift.org)
[](https://developer.apple.com/xcode)
[](https://developer.apple.com/macOS)
[](https://opensource.org/licenses/MIT)
This article refers to SwiftUI [apple example](https://github.com/Jinxiansen/SwiftUI/tree/doc) 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](https://swift.org) Grammar.
When learning and using `SwiftUI`, if you have any questions, you can join the SwiftUI QQ Group: **18552966** to discuss communication.
[中文版🇨🇳](README_CN.md)
### ⭐️ Stargazers over time
[](https://starchart.cc/Jinxiansen/SwiftUI)
### 💻 Requirements
- macOS 10.15
- Xcode 11.0
- iOS 13.0
## Directory:
### Basic View
* Text
- [Text](#Text)
- [TextField](#TextField)
- [SecureField](#SecureField)
* Image
- [Image](#Image)
- [WebImage](#WebImage)
* Button
- [Button](#Button)
- [PullDownButton](#PullDownButton)
- [ItemBasedPopUpButton](#ItemBasedPopUpButton)
- [NavigationButton](#NavigationButton)
- [PresentationButton](#PresentationButton)
- [EditButton](#EditButton)
- [PasteButton](#PasteButton)
* Picker
- [Picker](#Picker)
- [DatePicker](#DatePicker)
- [Toggle](#Toggle)
- [Slider](#Slider)
- [Stepper](#Stepper)
- [SegmentedControl](#SegmentedControl)
* Special Views
- [WebView](#WebView)
- [UIViewController](#UIViewController)
### Layout
* Stacks
- [HStack](#HStack)
- [VStack](#VStack)
- [ZStack](#ZStack)
* List
- [List](#List)
- [ScrollView](#ScrollView)
- [ForEach](#ForEach)
* Container Views
- [Group](#Group)
- [GroupBox](#GroupBox)
- [Section](#Section)
- [Form](#Form)
* Architectural Views
- [NavigationView](#NavigationView)
- [TabView](#TabView)
- [HSplitView](#HSplitView)
- [VSplitView](#VSplitView)
* Alert
- [Alert](#Alert)
- [Modal](#Modal)
- [Popover](#Popover)
- [Sheet](#Sheet)
- [ActionSheet](#ActionSheet)
### State and Data Flow
* Bindings
* [Binding](#Binding)
* Data-Dependent Views
* [State](#State)
* [ObjectBinding](#ObjectBinding)
* [EnvironmentObject](#EnvironmentObject)
* Environment Values
* [Environment](#Environment)
* [EnvironmentValues](#EnvironmentValues)
* ENavigation Models
* [DynamicNavigationDestinationLink](#DynamicNavigationDestinationLink)
* Preferences
* [LocalizedStringKey](#LocalizedStringKey)
* Transactions
* [Transaction](#Transaction)
### Gestures
* Basic Gestures
* [TapGesture](#TapGesture)
* [LongPressGesture](#LongPressGesture)
* [DragGesture](#DragGesture)
* [MagnificationGesture](#MagnificationGesture)
* [RotationGesture](#RotationGesture)
* Combined Gestures
* [SequenceGesture](#SequenceGesture)
* [SimultaneousGesture](#SimultaneousGesture)
* [ExclusiveGesture](#ExclusiveGesture)
* Custom Gestures
* [AnyGesture](#AnyGesture)
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:
```swift
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.
[🔝](#Text_D)
TextField
`TextField` is used to add a normal input box, which is often used as a text input.
Example:
```swift
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
[🔝](#Text_D)
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:
```swift
Image("icon")
.resizable()
.frame(width: 100,
height: 100,
alignment: .center)
```
View running results
[🔝](#Text_D)
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]((https://github.com/onevcat/Kingfisher)) in the `downloadWebImage ` function .
Example:
```swift
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
[🔝](#Text_D)
`Button` is used to respond to click events.
Example:
```swift
Button(action: {
print("Tap")
}) {
Text("I'm a Button")
}
```
View running results
[🔝](#Button_D)
Waiting for release.
Waiting for release.
`NavigationButtonPage ` is used to push to the next navigation page.
Example:
```swift
NavigationLink(destination: NavigationButtonPage()) {
Text("NavigationButton").bold()
.foregroundColor(.orange)
.font(.largeTitle)
}
.navigationBarTitle(Text("Page"))
```
View running results
[🔝](#Button_D)
`PresentationButton` ~~is used to pop up a page.~~ has deprecated, please use `NavigationLink`
[🔝](#Button_D)
`EditButton` is used to trigger the editing state, just use the `navigationBarItems` setting when using it.
Example:
```swift
navigationBarItems(trailing: EditButton())
```
View running results
[🔝](#Button_D)
Waiting for release.
Picker
`Picker` can customize the selector of the data source.
Example:
```swift
Picker(selection: $leftIndex, label: Text("Picker")) {
ForEach(0..
View running results
[🔝](#Picker_D)
DatePicker
`DatePicker` is used to select the absolute date of the control.
Example:
```swift
DatePicker(selection: $server.date,
in: server.spaceDate,
displayedComponents: .date, label: {
Text("")
})
```
View running results
[🔝](#Picker_D)
Toggle
`Toggle` is used to switch the selected state, for example:
```swift
Togglele(isOn: $isOn) {
Text("State: \(self.isOn == true ? "Open":"open")")
}.padding(20)
```
View running results
[🔝](#Picker_D)
Slider
`Slider ` A control for selecting values from a finite range of values, example:
```swift
Slider(value: $data.rating)
```
View running results
[🔝](#Picker_D)
Stepper
`Stepper ` is used to increase or decrease the value, example:
```swift
Stepper(value: $value, step: 2, onEditingChanged: { c in
print(c)
}) {
Text("Stepper Value: \(self.value)")
}.padding(50)
```
View running results
[🔝](#Picker_D)
SegmentedControl is deprecated
`SegmentedControl ` is used for segmentation condition selection, example:
```swift
SegmentedControl(selection: $currentIndex) {
ForEach(0..
View running results
[🔝](#Picker_D)
WebView
`WebView` is used to display an open web page, example:
```swift
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
[🔝](#Special_D)
UIViewController
`UIViewController` is used to display the **UIViewController** that opens **UIKit** in **SwiftUI** and opens the `SwiftUI` View in **UIViewController**.
Example:
First define:
```swift
struct ControllerPage : UIViewControllerRepresentable {
typealias UIViewControllerType = UIViewController
func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIViewController {
return T()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext) {
debugPrint("\(#function):\(type(of: T.self))")
}
}
```
Then use this:
```swift
NavigationButton(destination: ControllerPage()) {
PageRow(title: "UIViewController",subTitle: "Open UIViewController")
}
```
View running results
[🔝](#Special_D)
### Layout
HStack
`HStack` is used to arrange the subviews on a horizontal line.
Example:
```swift
HStack {
Text("made in China.")
Divider() // Just add a line.
Text("the People's Republic Of China.")
}
```
View running results
[🔝](#Layout_D)
VStack
`VStack` is used to arrange the subviews on a vertical line.
Example:
```swift
VStack {
Text("made in China.")
Divider() // Just add a line.
Text("the People's Republic Of China.")
}
```
View running results
[🔝](#Layout_D)
ZStack
`ZStack` is used to override the subview, aligned on two axes.
Example:
```swift
ZStack {
Text("made in China.")
Divider() // Just add a line.
Text("the People's Republic Of China.")
}
```
View running results
[🔝](#Layout_D)
List
`List` list container to display a list of data.
Examples:
```swift
List(0..<5) { item in
Text("Hello World !")
}.navigationBarTitle(Text("List"), displayMode: .large)
```
View running results
[🔝](#Layout_D)
`ScrollView` is a scroll view container.
Example:
```swift
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
[🔝](#Layout_D)
ForEach
`ForEach` is used to present a view based on a collection of existing data.
Example:
```swift
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
[🔝](#Layout_D)
Group
`Group` is used to aggregate multiple views, and the properties set on the Group will be applied to each child view.
Example:
```swift
Group {
Text("Hello World !")
Text("Hello World !")
}
```
View running results
[🔝](#Layout_D)
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:
```swift
Section(header: Text("I'm header"), footer: Text("I'm footer")) {
ForEach(0..<3) {
Text("Hello \($0)")
}
}
```
View running results
`Form` A container for grouping controls used for data entry, such as in settings or inspectors.
Example:
```swift
Form {
TextField("First Name", text: $firstName)
TextField("Last Name", text: $lastName)
}
```
View running results
[🔝](#Layout_D)
NavigationView
`NavigationView` is used to create a view container that contains the top navigation bar.
Example:
```swift
NavigationView {
Text("🧚♂️🧚♀️🧜♂️🧜♀️🧞♂️🧞♀️").blur(radius: 5)
Text("Swifter Swifter")
.bold()
.foregroundColor(.orange)
.font(.largeTitle)
}
.navigationBarTitle(Text("NavigationView"))
```
View running results
[🔝](#Layout_D)
TabView
`TabView` is used to create a view container that contains the bottom ** TabBar**.
Example:
```swift
TabView(selection: $index) {
ForEach(0..
View running results
[🔝](#Layout_D)
HSplitView
Waiting for release.
VSplitView
Waiting for release.
[🔝](#Layout_D)
Alert
`Alert` is used to display a bullet reminder that needs to be associated with a trigger event.
Example:
```swift
alert(isPresented: $showAlert, content: {
Alert(title: Text("确定要支付这100000000美元吗?"),
message: Text("请谨慎操作\n一旦确认,钱款将立即转入对方账户"),
primaryButton: .destructive(Text("确认")) { print("转出中...") },
secondaryButton: .cancel())
}).navigationBarTitle(Text("Alert"))
```
View running results
[🔝](#Alert_D)
ActionSheet
`ActionSheet` is used to pop up a selection box.
Example:
```swift
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:
```swift
.actionSheet(isPresented: $showSheet, content: {sheet})
```
View running results
[🔝](#Alert_D)
Modal
`Modal` is used to pop up a view.
Example:
```swift
Modal(Text("Modal View"),onDismiss: {
print("View Dismiss !")
})
```
View running results
[🔝](#Alert_D)
Popover
`Popover` is used to pop up a view, see the results below.
Example:
```swift
.popover(isPresented: $showPop, content: {
ImagePage()
})
```
View running results
[🔝](#Alert_D)
## 📎 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**](https://github.com/Jinxiansen/SwiftUI/issues/new) !
## ✉️ Contacts
email : hi@jinxiansen.com
微博 : [@晋先森](http://weibo.com/3205872327)
## 📄 License
SwiftUI is released under the [MIT license](LICENSE). See LICENSE for details.