国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

SwiftUI 2.0 備忘清單

該備忘單提供了使用 SwiftUI 的標簽的一些示例等

入門

介紹

SwiftUI 提供用于聲明應(yīng)用程序用戶界面的視圖、控件和布局結(jié)構(gòu)

import SwiftUI

struct AlbumDetail: View {
  var album: Album
  var body: some View {
    List(album.songs) { song in 
      HStack {
        Image(album.cover)
        VStack(alignment: .leading) {
          Text(song.title)
        }
      }
    }
  }
}

SwiftUI 與 UIKit 效果一致

View(視圖)

Text

要在UI中顯示文本,只需編寫:

Text("Hello World")

添加樣式

Text("Hello World")
    .font(.largeTitle)
    .foregroundColor(Color.green)
    .lineSpacing(50)
    .lineLimit(nil)
    .padding()

Text 設(shè)置文本格式

static let dateFormatter: DateFormatter = {
  let formatter = DateFormatter()
  formatter.dateStyle = .long
  return formatter
}()

var now = Date()
var body: some View {
  Text("Task due date: \(now, formatter: Self.dateFormatter)")
}

Label

可以使用以下代碼行在文本旁邊設(shè)置圖標。

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

文檔 - Label

可以設(shè)置URL,單擊后將重定向到瀏覽器。

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

文檔 - Label

Image 圖片

顯示與環(huán)境相關(guān)的圖像的視圖。

Image("foo") // 圖像名稱是foo

我們可以使用新的 SF Symbols

Image(systemName: "clock.fill")

您可以向系統(tǒng)圖標集添加樣式以匹配您使用的字體

Image(systemName: "cloud.heavyrain.fill")
    .foregroundColor(.red)
    .font(.title)
Image(systemName: "clock")
    .foregroundColor(.red)
    .font(Font.system(.largeTitle).bold())

為圖像添加樣式

Image("foo")
  .resizable() // 調(diào)整大小以便填充所有可用空間
  .aspectRatio(contentMode: .fit)

文檔 - Image

Shape

創(chuàng)建矩形的步驟

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

創(chuàng)建圓的步驟

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

文檔 - Image

ProgressView 進度視圖

顯示任務(wù)完成進度的視圖。

@State private var progress = 0.5

VStack {
    ProgressView(value: progress)
    Button("More", action: { progress += 0.05 })
}

通過應(yīng)用 CircularProgressViewStyle,可以將其用作 UIActivityIndicatorView。

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

文檔 - ProgressView

Map 地圖界面的視圖

顯示指定區(qū)域的地圖

import MapKit
@State var region = MKCoordinateRegion(center: .init(latitude: 37.334722, longitude: -122.008889), latitudinalMeters: 300, longitudinalMeters: 300)

Map(coordinateRegion: $region)

您可以通過指定 interactionModes(使用[]禁用所有交互)來控制地圖的交互。

struct PinItem: Identifiable {
    let id = UUID()
    let coordinate: CLLocationCoordinate2D
}

Map(coordinateRegion: $region, 
    interactionModes: [], 
    showsUserLocation: true, 
    userTrackingMode: nil, 
    annotationItems: [PinItem(coordinate: .init(latitude: 37.334722, longitude: -122.008889))]) { item in                    
    MapMarker(coordinate: item.coordinate)
}

文檔 - Map

Layout(布局)

Background

將圖像用作背景

Text("Hello World")
    .font(.largeTitle)
    .background(
        Image("hello_world")
            .resizable()
            .frame(width: 100, height: 100)
    )

VStack

以垂直線排列其子項的視圖

VStack (alignment: .center, spacing: 20){
    Text("Hello")
    Divider()
    Text("World")
}

創(chuàng)建靜態(tài)可滾動列表。文檔 - VStack

HStack

將其子級排列在一條水平線上的視圖。

創(chuàng)建靜態(tài)可滾動列表

HStack (alignment: .center, spacing: 20){
    Text("Hello")
    Divider()
    Text("World")
}

文檔 - HStack

LazyVStack

iOS 14 一種視圖,將其子級排列在垂直增長的線中,僅在需要時創(chuàng)建項。

ScrollView {
  LazyVStack(alignment: .leading) {
    ForEach(1...100, id: \.self) {
        Text("Row \($0)")
    }
  }
}

文檔 - LazyVStack

LazyHStack

將子項排列在水平增長的線中的視圖,僅在需要時創(chuàng)建項。

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

文檔 - LazyHStack

ZStack

覆蓋其子項的視圖,使子項在兩個軸上對齊。

ZStack {
    Text("Hello")
        .padding(10)
        .background(Color.red)
        .opacity(0.8)
    Text("World")
        .padding(20)
        .background(Color.red)
        .offset(x: 0, y: 40)
}

文檔 - ZStack

LazyVGrid

容器視圖,將其子視圖排列在垂直增長的網(wǎng)格中,僅在需要時創(chuàng)建項目。

var columns: [GridItem] = Array(repeating: .init(.fixed(20)), count: 5)

ScrollView {
    LazyVGrid(columns: columns) {
        ForEach((0...100), id: \.self) {
            Text("\($0)").background(Color.pink)
        }
    }
}

文檔 - LazyVGrid

LazyHGrid

一種容器視圖,將其子視圖排列在水平增長的網(wǎng)格中,僅在需要時創(chuàng)建項目。

var rows: [GridItem] =
  Array(
    repeating: .init(.fixed(20)), count: 2
  )

ScrollView(.horizontal) {
  LazyHGrid(rows: rows, alignment: .top) {
    ForEach((0...100), id: \.self) {
      Text("\($0)").background(Color.pink)
    }
  }
}

文檔 - LazyHGrid

Spacer

沿其包含的堆棧布局的主軸或如果不包含在堆棧中的兩個軸上擴展的靈活空間。

HStack {
    Image(systemName: "clock")
    Spacer()
    Text("Time")
}

文檔 - Spacer

Divider

可用于分隔其他內(nèi)容的視覺元素。

HStack {
    Image(systemName: "clock")
    Divider()
    Text("Time")
}.fixedSize()

文檔 - Divider

Input(輸入)

Toggle 開關(guān)選擇器

在打開和關(guān)閉狀態(tài)之間切換的控件。

@State var isShowing = true // toggle state

Toggle(isOn: $isShowing) {
    Text("Hello World")
}

如果您的 Toggle 的標簽只有 Text,則可以使用此更簡單的簽名進行初始化。

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

文檔 - Toggle

Button 按鈕控件

在觸發(fā)時執(zhí)行操作的控件。

Button(
    action: {
        print("did tap")
    },
    label: { Text("Click Me") }
)

如果 Button 的標簽僅為 Text,則可以使用此更簡單的簽名進行初始化。

Button("Click Me") {
    print("did tap")
}

您可以通過此按鈕了解一下

Button(action: {
    // 退出應(yīng)用
    NSApplication.shared.terminate(self)
}, label: {
    Image(systemName: "clock")
    Text("Click Me")
    Text("Subtitle")
})
.foregroundColor(Color.white)
.padding()
.background(Color.blue)
.cornerRadius(5)

文檔 - Button

TextField 輸入框

顯示可編輯文本界面的控件。

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

取消編輯框焦點樣式。

extension NSTextField { // << workaround !!!
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

如何居中放置 TextField 的文本

struct ContentView: View {
    @State var text: String = "TextField Text"
    var body: some View {
        TextField("Placeholder Text", text: $text)
            .padding(.all, 20)
            .multilineTextAlignment(.center)
    }
}

文檔 - TextField

SecureField 密碼輸入框

用戶安全地輸入私人文本的控件。

@State var password: String = "1234"    
var body: some View {
  SecureField($password)
    .textFieldStyle(RoundedBorderTextFieldStyle())
    .padding()
}

文檔 - SecureField

TextEditor 多行可滾動文本編輯器

可以顯示和編輯長格式文本的視圖。

@State private var fullText: String = "這是一些可編輯的文本..."

var body: some View {
  TextEditor(text: $fullText)
}

設(shè)置 TextEditor 背景顏色

extension NSTextView {
  open override var frame: CGRect {
    didSet {
      backgroundColor = .clear
//      drawsBackground = true
    }
  }
}
struct DetailContent: View {
  @State private var profileText: String = "輸入您的簡歷"
  var body: some View {
    VSplitView(){
      TextEditor(text: $profileText)
        .background(Color.red)
    }
  }
}

文檔 - TextEditor

DatePicker 日期控件

日期選擇器(DatePicker)的樣式也會根據(jù)其祖先而改變。 在 FormList 下,它顯示為單個列表行,您可以點擊以展開到日期選擇器(就像日歷應(yīng)用程序一樣)。

@State var selectedDate = Date()

var dateClosedRange: ClosedRange<Date> {
    let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
    let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
    return min...max
}
NavigationView {
  Form {
      Section {
          DatePicker(
              selection: $selectedDate,
              in: dateClosedRange,
              displayedComponents: .date,
              label: { Text("Due Date") }
          )
      }
  }
}

在表格和列表的外部,它顯示為普通的輪式拾取器

@State var selectedDate = Date()

var dateClosedRange: ClosedRange<Date> {
  let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
  let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
  return min...max
}

DatePicker(selection: $selectedDate, in: dateClosedRange,
  displayedComponents: [.hourAndMinute, .date],
  label: { Text("Due Date") }
)

如果 DatePicker 的標簽僅是純文本,則可以使用此更簡單的簽名進行初始化。

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

可以使用 ClosedRange,PartialRangeThroughPartialRangeFrom 來設(shè)置 minimumDatemaximumDate。

DatePicker("Minimum Date", selection: $selectedDate,
    in: Date()...,
    displayedComponents: [.date])

DatePicker("Maximum Date", selection: $selectedDate,
    in: ...Date(),
    displayedComponents: [.date])

文檔 - DatePicker

Slider 滑動輸入條

用于從值的有界線性范圍中選擇一個值的控件。

@State var progress: Float = 0

Slider(value: $progress,
  from: 0.0,
  through: 100.0,
  by: 5.0)

滑塊缺少 minimumValueImagemaximumValueImage,但是我們可以通過 HStack 輕松地復制它

@State var progress: Float = 0
HStack {
    Image(systemName: "sun.min")
    Slider(value: $progress,
        from: 0.0,
        through: 100.0,
        by: 5.0)
    Image(systemName: "sun.max.fill")
}.padding()

文檔 - Slider

Picker 選擇控件

用于從一組互斥值中進行選擇的控件。

選擇器樣式的更改基于其祖先,在 FormList 下,它顯示為單個列表行,您可以點擊以進入一個顯示所有可能選項的新屏幕。

NavigationView {
  Form {
    Section {
      Picker(selection: $selection,
        label: Text("Picker Name"),
        content: {
            Text("Value 1").tag(0)
            Text("Value 2").tag(1)
            Text("Value 3").tag(2)
            Text("Value 4").tag(3)
      })
    }
  }
}

您可以使用 .pickerStyle(WheelPickerStyle()) 覆蓋樣式。

@State var mapChoioce = 0
var settings = ["Map", "Transit", "Satellite"]
Picker("Options", selection: $mapChoioce) {
    ForEach(0 ..< settings.count) { index in
        Text(self.settings[index])
            .tag(index)
    }

}.pickerStyle(SegmentedPickerStyle())

SwiftUI 中,UISegmentedControl 只是 Picker的另一種樣式。分段控制(SegmentedControl)在 iOS 13 中也煥然一新。文檔 - Picker

Stepper 執(zhí)行語義遞增和遞減操作的控件

用于執(zhí)行語義遞增和遞減操作的控件。

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

如果 Stepper 的標簽只有 Text,則可以使用此更簡單的簽名進行初始化。

Stepper(
  "Quantity \(quantity)",
  value: $quantity,
  in: 0...10
)

如果要完全控制,他們可以提供裸機步進器,您可以在其中管理自己的數(shù)據(jù)源。

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

如果您還為帶有 step 的初始化程序的每個步驟指定了一個值的數(shù)量。

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

文檔 - Stepper

Tap

對于單次敲擊

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

用于雙擊

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

Gesture 手勢

手勢如輕敲手勢、長按手勢、拖拉手勢

Text("Tap")
  .gesture(
      TapGesture()
          .onEnded { _ in
              // do something
          }
  )
Text("Drag Me")
  .gesture(
      DragGesture(minimumDistance: 50)
          .onEnded { _ in
              // do something
          }
  )
Text("Long Press")
  .gesture(
      LongPressGesture(minimumDuration: 2)
          .onEnded { _ in
              // do something
          }
  )

OnChange

onChange 是一個新的視圖修改器,可用于所有 SwiftUI 視圖。它允許您偵聽狀態(tài)更改并相應(yīng)地對視圖執(zhí)行操作

TextEditor(text: $currentText)
  .onChange(of: clearText) { value in
      if clearText{
          currentText = ""
      }
  }

List(列表)

List 列表

一個容器,用于顯示排列在單列中的數(shù)據(jù)行。創(chuàng)建靜態(tài)可滾動列表

List {
    Text("Hello world")
    Text("Hello world")
    Text("Hello world")
}

創(chuàng)建動態(tài)列表

let names = ["John", "Apple", "Seed"]
List(names) { name in
    Text(name)
}

添加 Section

List {
    Section(header: Text("UIKit"), footer: Text("We will miss you")) {
        Text("UITableView")
    }

    Section(header: Text("SwiftUI"), footer: Text("A lot to learn")) {
        Text("List")
    }
}

可混合的列表

List {
    Text("Hello world")
    Image(systemName: "clock")
}

使其分組

添加 .listStyle(GroupedListStyle())

List {
  Section(header: Text("UIKit"),
    footer: Text("我們會想念你的")) {
      Text("UITableView")
  }

  Section(header: Text("SwiftUI"),
    footer: Text("要學的東西很多")) {
      Text("List")
  }
}.listStyle(GroupedListStyle())

插入分組

要使其插入分組(.insetGrouped),請?zhí)砑?.listStyle(GroupedListStyle()) 并強制使用常規(guī)水平尺寸類 .environment(\.horizontalSizeClass, .regular)。

List {
    Section(header: Text("UIKit"), footer: Text("We will miss you")) {
        Text("UITableView")
    }

    Section(header: Text("SwiftUI"), footer: Text("A lot to learn")) {
        Text("List")
    }
}.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)

插圖分組已添加到 iOS 13.2 中的 SwiftUI

iOS 14 中,我們?yōu)榇嗽O(shè)置了專用樣式。

.listStyle(InsetGroupedListStyle())

文檔 - List

ScrollView 滾動視圖

滾動視圖。

ScrollView(alwaysBounceVertical: true) {
    Image("foo")
    Text("Hello World")
}

文檔 - ScrollView

Containers(容器)

NavigationView 或多或少類似于 UINavigationController,它處理視圖之間的導航,顯示標題,將導航欄放在頂部。

NavigationView {
    Text("Hello")
        .navigationBarTitle(Text("World"), displayMode: .inline)
}

大標題使用 .large 將條形圖項添加到導航視圖

NavigationView {
  Text("Hello")
      .navigationBarTitle(Text("World"), displayMode: .inline)
      .navigationBarItems(
        trailing:
            Button(
                action: { print("Going to Setting") },
                label: { Text("Setting") }
            )
    )
}

按下時觸發(fā)導航演示的按鈕。這是 pushViewController 的替代品

NavigationView {
    NavigationLink(destination:
        Text("Detail")
        .navigationBarTitle(Text("Detail"))
    ) {
        Text("Push")
    }.navigationBarTitle(Text("Master"))
}

或者通過將組目標添加到自己的視圖 DetailView 中,使其更具可讀性

NavigationView {
    NavigationLink(destination: DetailView()) {
        Text("Push")
    }.navigationBarTitle(Text("Master"))
}

Group

Group 創(chuàng)建多個視圖作為一個視圖,同時也避免了 Stack 的10視圖最大限制

VStack {
    Group {
        Text("Hello")
        Text("Hello")
        Text("Hello")
    }
    Group {
        Text("Hello")
        Text("Hello")
    }
}

TabView

一個視圖,允許使用可交互的用戶界面元素在多個子視圖之間進行切換。

TabView {
    Text("First View")
        .font(.title)
        .tabItem({ Text("First") })
        .tag(0)
    Text("Second View")
        .font(.title)
        .tabItem({ Text("Second") })
        .tag(1)
}

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

TabView {
    Text("First View")
        .font(.title)
        .tabItem({
            Image(systemName: "circle")
            Text("First")
        })
        .tag(0)
    Text("Second View")
        .font(.title)
        .tabItem(VStack {
            Image("second")
            Text("Second")
        })
        .tag(1)
}

或者您可以省略 VStack

TabView {
    Text("First View")
        .font(.title)
        .tabItem({
            Image(systemName: "circle")
            Text("First")
        })
        .tag(0)
    Text("Second View")
        .font(.title)
        .tabItem({
            Image("second")
            Text("Second")
        })
        .tag(1)
}

Form

用于對用于數(shù)據(jù)輸入的控件(例如在設(shè)置或檢查器中)進行分組的容器。

NavigationView {
    Form {
        Section {
            Text("Plain Text")
            Stepper(value: $quantity, in: 0...10, label: { Text("Quantity") })
        }
        Section {
            DatePicker($date, label: { Text("Due Date") })
            Picker(selection: $selection, label:
                Text("Picker Name")
                , content: {
                    Text("Value 1").tag(0)
                    Text("Value 2").tag(1)
                    Text("Value 3").tag(2)
                    Text("Value 4").tag(3)
            })
        }
    }
}

您幾乎可以在此表單中放入任何內(nèi)容,它將為表單呈現(xiàn)適當?shù)臉邮?。文檔 - Form

Modal 過渡。我們可以顯示基于布爾的 Modal。

@State var isModal: Bool = false

var modal: some View {
    Text("Modal")
}

Button("Modal") {
    self.isModal = true
}.sheet(isPresented: $isModal, content: {
    self.modal
})

文檔 - Sheet

Alert

警報演示的容器。我們可以根據(jù)布爾值顯示Alert。

@State var isError: Bool = false

Button("Alert") {
    self.isError = true
}.alert(isPresented: $isError, content: {
    Alert(title: Text("Error"),
      message: Text("Error Reason"),
      dismissButton: .default(Text("OK"))
    )
})

Alert 也與可識別項綁定

@State var error: AlertError?

var body: some View {
    Button("Alert Error") {
        self.error = AlertError(reason: "Reason")
    }.alert(item: $error, content: { error in
        alert(reason: error.reason)
    })    
}

func alert(reason: String) -> Alert {
    Alert(title: Text("Error"),
            message: Text(reason),
            dismissButton: .default(Text("OK"))
    )
}

struct AlertError: Identifiable {
    var id: String {
        return reason
    }
    
    let reason: String
}

文檔 - Alert

ActionSheet

操作表演示文稿的存儲類型。我們可以顯示基于布爾值的 ActionSheet

@State var isSheet: Bool = false

var actionSheet: ActionSheet {
  ActionSheet(title: Text("Action"),
    message: Text("Description"),
    buttons: [
      .default(Text("OK"), action: {
          
      }),
      .destructive(Text("Delete"), action: {
          
      })
    ]
  )
}

Button("Action Sheet") {
    self.isSheet = true
}.actionSheet(isPresented: $isSheet,
  content: {
    self.actionSheet
})

ActionSheet 也與可識別項綁定

@State var sheetDetail: SheetDetail?

var body: some View {
    Button("Action Sheet") {
        self.sheetDetail = ModSheetDetail(body: "Detail")
    }.actionSheet(item: $sheetDetail, content: { detail in
        self.sheet(detail: detail.body)
    })
}

func sheet(detail: String) -> ActionSheet {
    ActionSheet(title: Text("Action"),
                message: Text(detail),
                buttons: [
                    .default(Text("OK"), action: {
                        
                    }),
                    .destructive(Text("Delete"), action: {
                        
                    })
                ]
    )
}

struct SheetDetail: Identifiable {
    var id: String {
        return body
    }
    let body: String
}

文檔 - ActionSheet

另見