SwiftUI 2.0 备忘清单

该备忘单提供了使用 SwiftUI 的标签的一些示例等

入门

介绍

SwiftUI 提供用于声明应用程序用户界面的视图、控件和布局结构

  1. import SwiftUI
  2. struct AlbumDetail: View {
  3. var album: Album
  4. var body: some View {
  5. List(album.songs) { song in
  6. HStack {
  7. Image(album.cover)
  8. VStack(alignment: .leading) {
  9. Text(song.title)
  10. }
  11. }
  12. }
  13. }
  14. }

SwiftUI 与 UIKit 效果一致

View(视图)

Text

要在UI中显示文本,只需编写:

  1. Text("Hello World")

添加样式

  1. Text("Hello World")
  2. .font(.largeTitle)
  3. .foregroundColor(Color.green)
  4. .lineSpacing(50)
  5. .lineLimit(nil)
  6. .padding()

Text 设置文本格式

  1. static let dateFormatter: DateFormatter = {
  2. let formatter = DateFormatter()
  3. formatter.dateStyle = .long
  4. return formatter
  5. }()
  6. var now = Date()
  7. var body: some View {
  8. Text("Task due date: \(now, formatter: Self.dateFormatter)")
  9. }

Label

可以使用以下代码行在文本旁边设置图标。

  1. Label("SwiftUI CheatSheet", systemImage: "up.icloud")

文档 - Label

Link

可以设置URL,单击后将重定向到浏览器。

  1. Link("Click me", destination: URL(string: "your_url")!)

文档 - Label

Image 图片

显示与环境相关的图像的视图。

  1. Image("foo") // 图像名称是foo

我们可以使用新的 SF Symbols

  1. Image(systemName: "clock.fill")

您可以向系统图标集添加样式以匹配您使用的字体

  1. Image(systemName: "cloud.heavyrain.fill")
  2. .foregroundColor(.red)
  3. .font(.title)
  4. Image(systemName: "clock")
  5. .foregroundColor(.red)
  6. .font(Font.system(.largeTitle).bold())

为图像添加样式

  1. Image("foo")
  2. .resizable() // 调整大小以便填充所有可用空间
  3. .aspectRatio(contentMode: .fit)

文档 - Image

Shape

创建矩形的步骤

  1. Rectangle()
  2. .fill(Color.red)
  3. .frame(width: 200, height: 200)

创建圆的步骤

  1. Circle()
  2. .fill(Color.blue)
  3. .frame(width: 50, height: 50)

文档 - Image

ProgressView 进度视图

显示任务完成进度的视图。

  1. @State private var progress = 0.5
  2. VStack {
  3. ProgressView(value: progress)
  4. Button("More", action: { progress += 0.05 })
  5. }

通过应用 CircularProgressViewStyle,可以将其用作 UIActivityIndicatorView

  1. ProgressView(value: progress)
  2. .progressViewStyle(CircularProgressViewStyle())

文档 - ProgressView

Map 地图界面的视图

显示指定区域的地图

  1. import MapKit
  2. @State var region = MKCoordinateRegion(center: .init(latitude: 37.334722, longitude: -122.008889), latitudinalMeters: 300, longitudinalMeters: 300)
  3. Map(coordinateRegion: $region)

您可以通过指定 interactionModes(使用[]禁用所有交互)来控制地图的交互。

  1. struct PinItem: Identifiable {
  2. let id = UUID()
  3. let coordinate: CLLocationCoordinate2D
  4. }
  5. Map(coordinateRegion: $region,
  6. interactionModes: [],
  7. showsUserLocation: true,
  8. userTrackingMode: nil,
  9. annotationItems: [PinItem(coordinate: .init(latitude: 37.334722, longitude: -122.008889))]) { item in
  10. MapMarker(coordinate: item.coordinate)
  11. }

文档 - Map

Layout(布局)

Background

将图像用作背景

  1. Text("Hello World")
  2. .font(.largeTitle)
  3. .background(
  4. Image("hello_world")
  5. .resizable()
  6. .frame(width: 100, height: 100)
  7. )

VStack

以垂直线排列其子项的视图

  1. VStack (alignment: .center, spacing: 20){
  2. Text("Hello")
  3. Divider()
  4. Text("World")
  5. }

创建静态可滚动列表。文档 - VStack

HStack

将其子级排列在一条水平线上的视图。

创建静态可滚动列表

  1. HStack (alignment: .center, spacing: 20){
  2. Text("Hello")
  3. Divider()
  4. Text("World")
  5. }

文档 - HStack

LazyVStack

iOS 14 一种视图,将其子级排列在垂直增长的线中,仅在需要时创建项。

  1. ScrollView {
  2. LazyVStack(alignment: .leading) {
  3. ForEach(1...100, id: \.self) {
  4. Text("Row \($0)")
  5. }
  6. }
  7. }

文档 - LazyVStack

LazyHStack

将子项排列在水平增长的线中的视图,仅在需要时创建项。

  1. ScrollView(.horizontal) {
  2. LazyHStack(alignment: .center, spacing: 20) {
  3. ForEach(1...100, id: \.self) {
  4. Text("Column \($0)")
  5. }
  6. }
  7. }

文档 - LazyHStack

ZStack

覆盖其子项的视图,使子项在两个轴上对齐。

  1. ZStack {
  2. Text("Hello")
  3. .padding(10)
  4. .background(Color.red)
  5. .opacity(0.8)
  6. Text("World")
  7. .padding(20)
  8. .background(Color.red)
  9. .offset(x: 0, y: 40)
  10. }

文档 - ZStack

LazyVGrid

容器视图,将其子视图排列在垂直增长的网格中,仅在需要时创建项目。

  1. var columns: [GridItem] = Array(repeating: .init(.fixed(20)), count: 5)
  2. ScrollView {
  3. LazyVGrid(columns: columns) {
  4. ForEach((0...100), id: \.self) {
  5. Text("\($0)").background(Color.pink)
  6. }
  7. }
  8. }

文档 - LazyVGrid

LazyHGrid

一种容器视图,将其子视图排列在水平增长的网格中,仅在需要时创建项目。

  1. var rows: [GridItem] =
  2. Array(
  3. repeating: .init(.fixed(20)), count: 2
  4. )
  5. ScrollView(.horizontal) {
  6. LazyHGrid(rows: rows, alignment: .top) {
  7. ForEach((0...100), id: \.self) {
  8. Text("\($0)").background(Color.pink)
  9. }
  10. }
  11. }

文档 - LazyHGrid

Spacer

沿其包含的堆栈布局的主轴或如果不包含在堆栈中的两个轴上扩展的灵活空间。

  1. HStack {
  2. Image(systemName: "clock")
  3. Spacer()
  4. Text("Time")
  5. }

文档 - Spacer

Divider

可用于分隔其他内容的视觉元素。

  1. HStack {
  2. Image(systemName: "clock")
  3. Divider()
  4. Text("Time")
  5. }.fixedSize()

文档 - Divider

Input(输入)

Toggle 开关选择器

在打开和关闭状态之间切换的控件。

  1. @State var isShowing = true // toggle state
  2. Toggle(isOn: $isShowing) {
  3. Text("Hello World")
  4. }

如果您的 Toggle 的标签只有 Text,则可以使用此更简单的签名进行初始化。

  1. Toggle("Hello World", isOn: $isShowing)

文档 - Toggle

Button 按钮控件

在触发时执行操作的控件。

  1. Button(
  2. action: {
  3. print("did tap")
  4. },
  5. label: { Text("Click Me") }
  6. )

如果 Button 的标签仅为 Text,则可以使用此更简单的签名进行初始化。

  1. Button("Click Me") {
  2. print("did tap")
  3. }

您可以通过此按钮了解一下

  1. Button(action: {
  2. // 退出应用
  3. NSApplication.shared.terminate(self)
  4. }, label: {
  5. Image(systemName: "clock")
  6. Text("Click Me")
  7. Text("Subtitle")
  8. })
  9. .foregroundColor(Color.white)
  10. .padding()
  11. .background(Color.blue)
  12. .cornerRadius(5)

文档 - Button

TextField 输入框

显示可编辑文本界面的控件。

  1. @State var name: String = "John"
  2. var body: some View {
  3. TextField("Name's placeholder", text: $name)
  4. .textFieldStyle(RoundedBorderTextFieldStyle())
  5. .padding()
  6. }

取消编辑框焦点样式。

  1. extension NSTextField { // << workaround !!!
  2. open override var focusRingType: NSFocusRingType {
  3. get { .none }
  4. set { }
  5. }
  6. }

如何居中放置 TextField 的文本

  1. struct ContentView: View {
  2. @State var text: String = "TextField Text"
  3. var body: some View {
  4. TextField("Placeholder Text", text: $text)
  5. .padding(.all, 20)
  6. .multilineTextAlignment(.center)
  7. }
  8. }

文档 - TextField

SecureField 密码输入框

用户安全地输入私人文本的控件。

  1. @State var password: String = "1234"
  2. var body: some View {
  3. SecureField($password)
  4. .textFieldStyle(RoundedBorderTextFieldStyle())
  5. .padding()
  6. }

文档 - SecureField

TextEditor 多行可滚动文本编辑器

可以显示和编辑长格式文本的视图。

  1. @State private var fullText: String = "这是一些可编辑的文本..."
  2. var body: some View {
  3. TextEditor(text: $fullText)
  4. }

设置 TextEditor 背景颜色

  1. extension NSTextView {
  2. open override var frame: CGRect {
  3. didSet {
  4. backgroundColor = .clear
  5. // drawsBackground = true
  6. }
  7. }
  8. }
  9. struct DetailContent: View {
  10. @State private var profileText: String = "输入您的简历"
  11. var body: some View {
  12. VSplitView(){
  13. TextEditor(text: $profileText)
  14. .background(Color.red)
  15. }
  16. }
  17. }

文档 - TextEditor

DatePicker 日期控件

日期选择器(DatePicker)的样式也会根据其祖先而改变。 在 FormList 下,它显示为单个列表行,您可以点击以展开到日期选择器(就像日历应用程序一样)。

  1. @State var selectedDate = Date()
  2. var dateClosedRange: ClosedRange<Date> {
  3. let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
  4. let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
  5. return min...max
  6. }
  7. NavigationView {
  8. Form {
  9. Section {
  10. DatePicker(
  11. selection: $selectedDate,
  12. in: dateClosedRange,
  13. displayedComponents: .date,
  14. label: { Text("Due Date") }
  15. )
  16. }
  17. }
  18. }

在表格和列表的外部,它显示为普通的轮式拾取器

  1. @State var selectedDate = Date()
  2. var dateClosedRange: ClosedRange<Date> {
  3. let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
  4. let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
  5. return min...max
  6. }
  7. DatePicker(selection: $selectedDate, in: dateClosedRange,
  8. displayedComponents: [.hourAndMinute, .date],
  9. label: { Text("Due Date") }
  10. )

如果 DatePicker 的标签仅是纯文本,则可以使用此更简单的签名进行初始化。

  1. DatePicker("Due Date", selection: $selectedDate, in: dateClosedRange,
  2. displayedComponents: [.hourAndMinute, .date])

可以使用 ClosedRangePartialRangeThroughPartialRangeFrom 来设置 minimumDatemaximumDate

  1. DatePicker("Minimum Date", selection: $selectedDate,
  2. in: Date()...,
  3. displayedComponents: [.date])
  4. DatePicker("Maximum Date", selection: $selectedDate,
  5. in: ...Date(),
  6. displayedComponents: [.date])

文档 - DatePicker

Slider 滑动输入条

用于从值的有界线性范围中选择一个值的控件。

  1. @State var progress: Float = 0
  2. Slider(value: $progress,
  3. from: 0.0,
  4. through: 100.0,
  5. by: 5.0)

滑块缺少 minimumValueImagemaximumValueImage,但是我们可以通过 HStack 轻松地复制它

  1. @State var progress: Float = 0
  2. HStack {
  3. Image(systemName: "sun.min")
  4. Slider(value: $progress,
  5. from: 0.0,
  6. through: 100.0,
  7. by: 5.0)
  8. Image(systemName: "sun.max.fill")
  9. }.padding()

文档 - Slider

Picker 选择控件

用于从一组互斥值中进行选择的控件。

选择器样式的更改基于其祖先,在 FormList 下,它显示为单个列表行,您可以点击以进入一个显示所有可能选项的新屏幕。

  1. NavigationView {
  2. Form {
  3. Section {
  4. Picker(selection: $selection,
  5. label: Text("Picker Name"),
  6. content: {
  7. Text("Value 1").tag(0)
  8. Text("Value 2").tag(1)
  9. Text("Value 3").tag(2)
  10. Text("Value 4").tag(3)
  11. })
  12. }
  13. }
  14. }

您可以使用 .pickerStyle(WheelPickerStyle()) 覆盖样式。

  1. @State var mapChoioce = 0
  2. var settings = ["Map", "Transit", "Satellite"]
  3. Picker("Options", selection: $mapChoioce) {
  4. ForEach(0 ..< settings.count) { index in
  5. Text(self.settings[index])
  6. .tag(index)
  7. }
  8. }.pickerStyle(SegmentedPickerStyle())

SwiftUI 中,UISegmentedControl 只是 Picker的另一种样式。分段控制(SegmentedControl)在 iOS 13 中也焕然一新。文档 - Picker

Stepper 执行语义递增和递减操作的控件

用于执行语义递增和递减操作的控件。

  1. @State var quantity: Int = 0
  2. Stepper(
  3. value: $quantity,
  4. in: 0...10,
  5. label: { Text("Quantity \(quantity)")}
  6. )

如果 Stepper 的标签只有 Text,则可以使用此更简单的签名进行初始化。

  1. Stepper(
  2. "Quantity \(quantity)",
  3. value: $quantity,
  4. in: 0...10
  5. )

如果要完全控制,他们可以提供裸机步进器,您可以在其中管理自己的数据源。

  1. @State var quantity: Int = 0
  2. Stepper(onIncrement: {
  3. self.quantity += 1
  4. }, onDecrement: {
  5. self.quantity -= 1
  6. }, label: { Text("Quantity \(quantity)") })

如果您还为带有 step 的初始化程序的每个步骤指定了一个值的数量。

  1. Stepper(
  2. value: $quantity, in: 0...10, step: 2
  3. ) {
  4. Text("Quantity \(quantity)")
  5. }

文档 - Stepper

Tap

对于单次敲击

  1. Text("Tap me!").onTapGesture {
  2. print("Tapped!")
  3. }

用于双击

  1. Text("Tap me!").onTapGesture(count: 2) {
  2. print("Tapped!")
  3. }

Gesture 手势

手势如轻敲手势、长按手势、拖拉手势

  1. Text("Tap")
  2. .gesture(
  3. TapGesture()
  4. .onEnded { _ in
  5. // do something
  6. }
  7. )
  8. Text("Drag Me")
  9. .gesture(
  10. DragGesture(minimumDistance: 50)
  11. .onEnded { _ in
  12. // do something
  13. }
  14. )
  15. Text("Long Press")
  16. .gesture(
  17. LongPressGesture(minimumDuration: 2)
  18. .onEnded { _ in
  19. // do something
  20. }
  21. )

OnChange

onChange 是一个新的视图修改器,可用于所有 SwiftUI 视图。它允许您侦听状态更改并相应地对视图执行操作

  1. TextEditor(text: $currentText)
  2. .onChange(of: clearText) { value in
  3. if clearText{
  4. currentText = ""
  5. }
  6. }

List(列表)

List 列表

一个容器,用于显示排列在单列中的数据行。创建静态可滚动列表

  1. List {
  2. Text("Hello world")
  3. Text("Hello world")
  4. Text("Hello world")
  5. }

创建动态列表

  1. let names = ["John", "Apple", "Seed"]
  2. List(names) { name in
  3. Text(name)
  4. }

添加 Section

  1. List {
  2. Section(header: Text("UIKit"), footer: Text("We will miss you")) {
  3. Text("UITableView")
  4. }
  5. Section(header: Text("SwiftUI"), footer: Text("A lot to learn")) {
  6. Text("List")
  7. }
  8. }

可混合的列表

  1. List {
  2. Text("Hello world")
  3. Image(systemName: "clock")
  4. }

使其分组

添加 .listStyle(GroupedListStyle())

  1. List {
  2. Section(header: Text("UIKit"),
  3. footer: Text("我们会想念你的")) {
  4. Text("UITableView")
  5. }
  6. Section(header: Text("SwiftUI"),
  7. footer: Text("要学的东西很多")) {
  8. Text("List")
  9. }
  10. }.listStyle(GroupedListStyle())

插入分组

要使其插入分组(.insetGrouped),请添加 .listStyle(GroupedListStyle()) 并强制使用常规水平尺寸类 .environment(\.horizontalSizeClass, .regular)

  1. List {
  2. Section(header: Text("UIKit"), footer: Text("We will miss you")) {
  3. Text("UITableView")
  4. }
  5. Section(header: Text("SwiftUI"), footer: Text("A lot to learn")) {
  6. Text("List")
  7. }
  8. }.listStyle(GroupedListStyle())
  9. .environment(\.horizontalSizeClass, .regular)

插图分组已添加到 iOS 13.2 中的 SwiftUI

iOS 14 中,我们为此设置了专用样式。

  1. .listStyle(InsetGroupedListStyle())

文档 - List

ScrollView 滚动视图

滚动视图。

  1. ScrollView(alwaysBounceVertical: true) {
  2. Image("foo")
  3. Text("Hello World")
  4. }

文档 - ScrollView

Containers(容器)

NavigationView

NavigationView 或多或少类似于 UINavigationController,它处理视图之间的导航,显示标题,将导航栏放在顶部。

  1. NavigationView {
  2. Text("Hello")
  3. .navigationBarTitle(Text("World"), displayMode: .inline)
  4. }

大标题使用 .large 将条形图项添加到导航视图

  1. NavigationView {
  2. Text("Hello")
  3. .navigationBarTitle(Text("World"), displayMode: .inline)
  4. .navigationBarItems(
  5. trailing:
  6. Button(
  7. action: { print("Going to Setting") },
  8. label: { Text("Setting") }
  9. )
  10. )
  11. }

NavigationLink

按下时触发导航演示的按钮。这是 pushViewController 的替代品

  1. NavigationView {
  2. NavigationLink(destination:
  3. Text("Detail")
  4. .navigationBarTitle(Text("Detail"))
  5. ) {
  6. Text("Push")
  7. }.navigationBarTitle(Text("Master"))
  8. }

或者通过将组目标添加到自己的视图 DetailView 中,使其更具可读性

  1. NavigationView {
  2. NavigationLink(destination: DetailView()) {
  3. Text("Push")
  4. }.navigationBarTitle(Text("Master"))
  5. }

Group

Group 创建多个视图作为一个视图,同时也避免了 Stack 的10视图最大限制

  1. VStack {
  2. Group {
  3. Text("Hello")
  4. Text("Hello")
  5. Text("Hello")
  6. }
  7. Group {
  8. Text("Hello")
  9. Text("Hello")
  10. }
  11. }

TabView

一个视图,允许使用可交互的用户界面元素在多个子视图之间进行切换。

  1. TabView {
  2. Text("First View")
  3. .font(.title)
  4. .tabItem({ Text("First") })
  5. .tag(0)
  6. Text("Second View")
  7. .font(.title)
  8. .tabItem({ Text("Second") })
  9. .tag(1)
  10. }

图像和文本在一起。 您可以在此处使用 SF Symbol

  1. TabView {
  2. Text("First View")
  3. .font(.title)
  4. .tabItem({
  5. Image(systemName: "circle")
  6. Text("First")
  7. })
  8. .tag(0)
  9. Text("Second View")
  10. .font(.title)
  11. .tabItem(VStack {
  12. Image("second")
  13. Text("Second")
  14. })
  15. .tag(1)
  16. }

或者您可以省略 VStack

  1. TabView {
  2. Text("First View")
  3. .font(.title)
  4. .tabItem({
  5. Image(systemName: "circle")
  6. Text("First")
  7. })
  8. .tag(0)
  9. Text("Second View")
  10. .font(.title)
  11. .tabItem({
  12. Image("second")
  13. Text("Second")
  14. })
  15. .tag(1)
  16. }

Form

用于对用于数据输入的控件(例如在设置或检查器中)进行分组的容器。

  1. NavigationView {
  2. Form {
  3. Section {
  4. Text("Plain Text")
  5. Stepper(value: $quantity, in: 0...10, label: { Text("Quantity") })
  6. }
  7. Section {
  8. DatePicker($date, label: { Text("Due Date") })
  9. Picker(selection: $selection, label:
  10. Text("Picker Name")
  11. , content: {
  12. Text("Value 1").tag(0)
  13. Text("Value 2").tag(1)
  14. Text("Value 3").tag(2)
  15. Text("Value 4").tag(3)
  16. })
  17. }
  18. }
  19. }

您几乎可以在此表单中放入任何内容,它将为表单呈现适当的样式。文档 - Form

Modal

Modal 过渡。我们可以显示基于布尔的 Modal。

  1. @State var isModal: Bool = false
  2. var modal: some View {
  3. Text("Modal")
  4. }
  5. Button("Modal") {
  6. self.isModal = true
  7. }.sheet(isPresented: $isModal, content: {
  8. self.modal
  9. })

文档 - Sheet

Alert

警报演示的容器。我们可以根据布尔值显示Alert。

  1. @State var isError: Bool = false
  2. Button("Alert") {
  3. self.isError = true
  4. }.alert(isPresented: $isError, content: {
  5. Alert(title: Text("Error"),
  6. message: Text("Error Reason"),
  7. dismissButton: .default(Text("OK"))
  8. )
  9. })

Alert 也与可识别项绑定

  1. @State var error: AlertError?
  2. var body: some View {
  3. Button("Alert Error") {
  4. self.error = AlertError(reason: "Reason")
  5. }.alert(item: $error, content: { error in
  6. alert(reason: error.reason)
  7. })
  8. }
  9. func alert(reason: String) -> Alert {
  10. Alert(title: Text("Error"),
  11. message: Text(reason),
  12. dismissButton: .default(Text("OK"))
  13. )
  14. }
  15. struct AlertError: Identifiable {
  16. var id: String {
  17. return reason
  18. }
  19. let reason: String
  20. }

文档 - Alert

ActionSheet

操作表演示文稿的存储类型。我们可以显示基于布尔值的 ActionSheet

  1. @State var isSheet: Bool = false
  2. var actionSheet: ActionSheet {
  3. ActionSheet(title: Text("Action"),
  4. message: Text("Description"),
  5. buttons: [
  6. .default(Text("OK"), action: {
  7. }),
  8. .destructive(Text("Delete"), action: {
  9. })
  10. ]
  11. )
  12. }
  13. Button("Action Sheet") {
  14. self.isSheet = true
  15. }.actionSheet(isPresented: $isSheet,
  16. content: {
  17. self.actionSheet
  18. })

ActionSheet 也与可识别项绑定

  1. @State var sheetDetail: SheetDetail?
  2. var body: some View {
  3. Button("Action Sheet") {
  4. self.sheetDetail = ModSheetDetail(body: "Detail")
  5. }.actionSheet(item: $sheetDetail, content: { detail in
  6. self.sheet(detail: detail.body)
  7. })
  8. }
  9. func sheet(detail: String) -> ActionSheet {
  10. ActionSheet(title: Text("Action"),
  11. message: Text(detail),
  12. buttons: [
  13. .default(Text("OK"), action: {
  14. }),
  15. .destructive(Text("Delete"), action: {
  16. })
  17. ]
  18. )
  19. }
  20. struct SheetDetail: Identifiable {
  21. var id: String {
  22. return body
  23. }
  24. let body: String
  25. }

文档 - ActionSheet

另见