swifttool

SwiftUI框架详细解析 (二十七) —— 基于SwiftUI

2021-03-21  本文已影响0人  刀客传奇

版本记录

版本号 时间
V1.0 2021.03.21 星期日

前言

今天翻阅苹果的API文档,发现多了一个框架SwiftUI,这里我们就一起来看一下这个框架。感兴趣的看下面几篇文章。
1. SwiftUI框架详细解析 (一) —— 基本概览(一)
2. SwiftUI框架详细解析 (二) —— 基于SwiftUI的闪屏页的创建(一)
3. SwiftUI框架详细解析 (三) —— 基于SwiftUI的闪屏页的创建(二)
4. SwiftUI框架详细解析 (四) —— 使用SwiftUI进行苹果登录(一)
5. SwiftUI框架详细解析 (五) —— 使用SwiftUI进行苹果登录(二)
6. SwiftUI框架详细解析 (六) —— 基于SwiftUI的导航的实现(一)
7. SwiftUI框架详细解析 (七) —— 基于SwiftUI的导航的实现(二)
8. SwiftUI框架详细解析 (八) —— 基于SwiftUI的动画的实现(一)
9. SwiftUI框架详细解析 (九) —— 基于SwiftUI的动画的实现(二)
10. SwiftUI框架详细解析 (十) —— 基于SwiftUI构建各种自定义图表(一)
11. SwiftUI框架详细解析 (十一) —— 基于SwiftUI构建各种自定义图表(二)
12. SwiftUI框架详细解析 (十二) —— 基于SwiftUI创建Mind-Map UI(一)
13. SwiftUI框架详细解析 (十三) —— 基于SwiftUI创建Mind-Map UI(二)
14. SwiftUI框架详细解析 (十四) —— 基于Firebase Cloud Firestore的SwiftUI iOS程序的持久性添加(一)
15. SwiftUI框架详细解析 (十五) —— 基于Firebase Cloud Firestore的SwiftUI iOS程序的持久性添加(二)
16. SwiftUI框架详细解析 (十六) —— 基于SwiftUI简单App的Dependency Injection应用(一)
17. SwiftUI框架详细解析 (十七) —— 基于SwiftUI简单App的Dependency Injection应用(二)
18. SwiftUI框架详细解析 (十八) —— Firebase Remote Config教程(一)
19. SwiftUI框架详细解析 (十九) —— Firebase Remote Config教程(二)
20. SwiftUI框架详细解析 (二十) —— 基于SwiftUI的Document-Based App的创建(一)
21. SwiftUI框架详细解析 (二十一) —— 基于SwiftUI的Document-Based App的创建(二)
22. SwiftUI框架详细解析 (二十二) —— 基于SwiftUI的AWS AppSync框架的使用(一)
23. SwiftUI框架详细解析 (二十三) —— 基于SwiftUI的AWS AppSync框架的使用(二)
24. SwiftUI框架详细解析 (二十四) —— 基于SwiftUI的编辑占位符的使用(一)
25. SwiftUI框架详细解析 (二十五) —— 基于SwiftUI的编辑占位符的使用(二)
26. SwiftUI框架详细解析 (二十六) —— 基于SwiftUI和Xcode12的Multiplatform App的搭建(一)

源码

1. Swift

首先看下工程组织结构

下面就是源码了

1. ContentView.swift
import SwiftUI

enum NavigationItem {
  case all
  case favorites
}

struct ContentView: View {
  var body: some View {
    GemListViewer()
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    NavigationView {
      ContentView()
        .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
  }
}
2. MainColorText.swift
import SwiftUI

struct MainColorText: View {
  let colorName: String

  var body: some View {
    Text("Main color: ") +
      Text(colorName.capitalized)
        .foregroundColor(Color(colorName))
        .bold()
        .font(.subheadline)
  }
}

struct MainColorText_Previews: PreviewProvider {
  static var previews: some View {
    MainColorText(colorName: "rose")
      .previewLayout(.sizeThatFits)
  }
}
3. GemRow.swift
import SwiftUI

struct GemRow: View {
  @ObservedObject var gem: Gem

  var body: some View {
    HStack {
      Image(gem.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 64, height: 64)
      VStack(alignment: .leading) {
        Text(gem.name)
          .font(.title)
          .bold()
        MainColorText(colorName: gem.mainColor)
      }
    }
  }
}

struct GemRow_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      GemRow(gem: roseGem)
      GemRow(gem: lapisGem)
    }
    .previewLayout(.sizeThatFits)
  }
}
4. DetailsView.swift
import SwiftUI

struct DetailsView: View {
  @Environment(\.managedObjectContext) private var viewContext
  @ObservedObject var gem: Gem

  var body: some View {
    ScrollView {
      VStack(spacing: 10) {
        Image(gem.imageName)
          .resizable()
          .aspectRatio(contentMode: .fit)
          .frame(width: 200, height: 200)
        Text(gem.name)
          .foregroundColor(Color(gem.mainColor))
          .font(.largeTitle)
          .bold()
        Text(gem.info)
          .font(.title2)
          .multilineTextAlignment(.leading)
        Divider()
        VStack(alignment: .leading) {
          MainColorText(colorName: gem.mainColor)
          Text("Crystal system: \(gem.crystalSystem)")
          Text("Chemical formula: \(gem.formula)")
          Text("Hardness (Mohs hardness scale): \(gem.hardness)")
          Text("Transparency: \(gem.transparency)")
        }
        .padding(.top)
      }
      .padding()
    }
    .navigationTitle(gem.name)
    .toolbar {
      ToolbarItem {
        Button(action: toggleFavorite) {
          Label(
            gem.favorite ? "Unfavorite" : "Favorite",
            systemImage: gem.favorite ? "heart.fill" : "heart"
          )
          .foregroundColor(.pink)
        }
      }
    }
  }

  func toggleFavorite() {
    gem.favorite.toggle()
    try? viewContext.save()
  }
}

struct DetailsView_Previews: PreviewProvider {
  static var previews: some View {
    NavigationView {
      DetailsView(gem: roseGem)
        .environment(
          \.managedObjectContext,
          PersistenceController.preview.container.viewContext
        )
    }
  }
}
5. GemList.swift
import SwiftUI

struct GemList: View {
  @FetchRequest(
    sortDescriptors: [
      NSSortDescriptor(
        keyPath: \Gem.timestamp,
        ascending: true)
    ],
    animation: .default)
  private var gems: FetchedResults<Gem>

  @State private var selectedGem: Gem?

  var body: some View {
    List(selection: $selectedGem) {
      ForEach(gems) { gem in
        NavigationLink(
          destination: DetailsView(gem: gem),
          tag: gem,
          selection: $selectedGem
        ) {
          GemRow(gem: gem)
        }
        .tag(gem)
      }
    }
    .navigationTitle("Gems")
    .frame(minWidth: 250)
  }
}

struct GemList_Previews: PreviewProvider {
  static var previews: some View {
    NavigationView {
      GemList()
        .environment(
          \.managedObjectContext,
          PersistenceController.preview.container.viewContext
        )
    }
  }
}`
6. FavoriteGems.swift
import SwiftUI

struct FavoriteGems: View {
  @FetchRequest(
    sortDescriptors: [
      NSSortDescriptor(
        keyPath: \Gem.timestamp,
        ascending: true)
    ],
    predicate: NSPredicate(format: "favorite == true"),
    animation: .default)
  private var gems: FetchedResults<Gem>

  @State private var selectedGem: Gem?

  var body: some View {
    List(selection: $selectedGem) {
      if gems.isEmpty {
        Text("Add some gems to your Favorites!")
          .foregroundColor(.secondary)
          .frame(maxWidth: .infinity, maxHeight: .infinity)
      }
      ForEach(gems) { gem in
        NavigationLink(
          destination: DetailsView(gem: gem),
          tag: gem,
          selection: $selectedGem
        ) {
          GemRow(gem: gem)
        }
        .tag(gem)
      }
    }
    .navigationTitle("Favorites")
    .frame(minWidth: 250)
  }
}

struct FavoriteGems_Previews: PreviewProvider {
  static var previews: some View {
    NavigationView {
      FavoriteGems()
    }
  }
}
7. SettingsView.swift
import SwiftUI

struct SettingsView: View {
  @State var showAlert = false

  var appVersion: String {
    Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  }

  func showClearAlert() {
    showAlert.toggle()
  }

  func clearFavorites() {
    let viewContext = PersistenceController.shared.container.viewContext
    let gemEntity = Gem.entity()
    let batchUpdateRequest = NSBatchUpdateRequest(entity: gemEntity)
    batchUpdateRequest.propertiesToUpdate = ["favorite": false]

    do {
      try viewContext.execute(batchUpdateRequest)
    } catch {
      print("Handle Error: \(error.localizedDescription)")
    }
  }

  var body: some View {
    ScrollView {
      VStack {
        Text("Settings")
          .font(.largeTitle)
          .frame(maxWidth: .infinity, alignment: .leading)
          .padding()
        Image("rw-logo")
          .resizable()
          .aspectRatio(contentMode: .fill)
          .frame(width: 400, height: 400)
        Text("RayGem")
          .font(.largeTitle)
        Text("Gem Version: \(appVersion)")
        Section {
          Button(action: showClearAlert) {
            Label("Clear Favorites", systemImage: "trash")
          }
        }
      }
      .frame(width: 600, height: 600)
      .alert(isPresented: $showAlert) {
        Alert(
          title: Text("Are you sure?")
            .font(.title)
            .foregroundColor(.red),
          message: Text("This action cannot be undone."),
          primaryButton: .cancel(),
          secondaryButton: .destructive(
            Text("Clear"),
            action: clearFavorites))
      }
    }
  }
}

struct SettingsView_Previews: PreviewProvider {
  static var previews: some View {
    SettingsView()
  }
}
8. Gem+CoreDataClass.swift
import Foundation
import CoreData

@objc(Gem)
public class Gem: NSManagedObject { }
9. Gem+CoreDataProperties.swift
import Foundation
import CoreData

extension Gem {
  @nonobjc
  public class func fetchRequest() -> NSFetchRequest<Gem> {
    return NSFetchRequest<Gem>(entityName: "Gem")
  }

  @NSManaged public var info: String
  @NSManaged public var name: String
  @NSManaged public var timestamp: Date
  @NSManaged public var favorite: Bool
  @NSManaged public var imageName: String
  @NSManaged public var mainColor: String
  @NSManaged public var crystalSystem: String
  @NSManaged public var formula: String
  @NSManaged public var hardness: String
  @NSManaged public var transparency: String
}

extension Gem: Identifiable { }
10. PreviewProvider+Gem.swift
import SwiftUI

extension PreviewProvider {
  static var roseGem: Gem {
    let gem = Gem(context: PersistenceController.preview.container.viewContext)
    gem.name = "Rose Quartz"
    gem.info = "A pinkish quartz, found in many shapes and sizes. Rose Quartz was once the leader of the Crystal Gems."
    gem.imageName = "rose"
    gem.mainColor = "rose"
    gem.crystalSystem = "Hexagonal crystal system"
    gem.formula = "SiO₂"
    gem.hardness = "7"
    gem.transparency = "Translucent, Transparent"
    gem.timestamp = Date()
    return gem
  }

  static var lapisGem: Gem {
    let gem = Gem(context: PersistenceController.preview.container.viewContext)
    gem.name = "Lapis Lazuli"
        gem.info = """
        Lapis lazuli is a deep-blue rock used to create semiprecious stones and artifacts.
        Lapis Lazuli once terraformed planets for Homeworld.
        """
    gem.imageName = "lapis"
    gem.mainColor = "blue"
    gem.crystalSystem = "Cubic crystal system"
    gem.formula = "(Na,Ca)₈Al₆Si₆O₂₄ (S,SO)₄"
    gem.hardness = "5 – 5.5"
    gem.transparency = "Opaque"
    gem.timestamp = Date()
    gem.favorite = true
    return gem
  }
}
11. PersistenceController+Gem.swift
import CoreData

extension PersistenceController {
  func createInitialGems(viewContext: NSManagedObjectContext) {
    createFirstGems(viewContext: viewContext)
    createSecondGems(viewContext: viewContext)
  }

  func createFirstGems(viewContext: NSManagedObjectContext) {
    let rose = Gem(context: viewContext)
    rose.name = "Rose Quartz"
    rose.info = "A pinkish quartz, found in many shapes and sizes. Rose Quartz was once the leader of the Crystal Gems."
    rose.imageName = "rose"
    rose.mainColor = "rose"
    rose.crystalSystem = "Hexagonal crystal system"
    rose.formula = "SiO₂"
    rose.hardness = "7"
    rose.transparency = "Translucent, Transparent"
    rose.timestamp = Date()

    let lapis = Gem(context: viewContext)
    lapis.name = "Lapis Lazuli"
    lapis.info = """
    Lapis lazuli is a deep-blue rock used to create semiprecious stones and artifacts.
    Lapis Lazuli once terraformed planets for Homeworld.
    """
    lapis.imageName = "lapis"
    lapis.mainColor = "blue"
    lapis.crystalSystem = "Cubic crystal system"
    lapis.formula = "(Na,Ca)₈Al₆Si₆O₂₄ (S,SO)₄"
    lapis.hardness = "5 – 5.5"
    lapis.transparency = "Opaque"
    lapis.timestamp = Date()

    let ruby = Gem(context: viewContext)
    ruby.name = "Ruby"
    ruby.info = """
    Ruby is a blood red gemstone.
    Rubies were used in armor and placed under the foundation of buildings to ensure good fortune.
    They are great warriors but usually hotheaded and easily distracted.
    """
    ruby.imageName = "ruby"
    ruby.mainColor = "ruby"
    ruby.crystalSystem = "Hexagonal crystal system"
    ruby.formula = "Al₂O₃"
    ruby.hardness = "9"
    ruby.transparency = "Opaque, Transparent"
    ruby.timestamp = Date()

    let sapphire = Gem(context: viewContext)
    sapphire.name = "Sapphire"
    sapphire.info = """
    Sapphire is a blue precious gemstone not typically used in costume jewelry.
    Sapphire has the power to see branches of the future.
    """
    sapphire.imageName = "sapphire"
    sapphire.mainColor = "blue"
    sapphire.crystalSystem = "Hexagonal crystal system"
    sapphire.formula = "Al₂O₃"
    sapphire.hardness = "9"
    sapphire.transparency = "Opaque, Transparent"
    sapphire.timestamp = Date()
  }

  func createSecondGems(viewContext: NSManagedObjectContext) {
    let amethyst = Gem(context: viewContext)
    amethyst.name = "Amethyst"
    amethyst.info = """
    Amethyst is a violet variety of quartz.
    Considered semiprecious, it is often used in jewelry.
    The name derives from the Greek a-methustos, not drunk.
    Ancient Greeks believed this gem prevented insobriety and often carved wine goblets from it.
    Amethysts are big strong warriors, but the little ones are even stronger.
    """
    amethyst.imageName = "amethyst"
    amethyst.mainColor = "purple"
    amethyst.crystalSystem = "Hexagonal crystal system"
    amethyst.formula = "SiO₂"
    amethyst.hardness = "7"
    amethyst.transparency = "Translucent, Transparent"
    amethyst.timestamp = Date()

    let pearl = Gem(context: viewContext)
    pearl.name = "Pearl"
    pearl.info = """
    Pearl is a hard, usually white- or beige-colored substance, produced inside an oyster.
    Pearls are ground into cosmetics and sewn onto clothing.
    They were created to serve, due to their caring nature, but make no mistake: once free, Pearls are loyal leaders.
    """
    pearl.imageName = "pearl"
    pearl.mainColor = "beige"
    pearl.crystalSystem = "Hexagonal crystal system"
    pearl.formula = "Calcium carbonate, CaCO3 Conchiolin"
    pearl.hardness = "2.5 – 4.5"
    pearl.transparency = "Opaque"
    pearl.timestamp = Date()

    let peridot = Gem(context: viewContext)
    peridot.name = "Peridot"
    peridot.info = """
    Peridot is a light green gem. In the Middle Ages, peridots were believed to have healing powers.
    Peridots may seem rather cold, but once they get to know you, they get really attached.
    They are very smart and can handle technology very well.
    """
    peridot.imageName = "peridot"
    peridot.mainColor = "green"
    peridot.crystalSystem = "Orthorhombic crystal system"
    peridot.formula = "(Mg,Fe)₂SiO₄"
    peridot.hardness = "6.5 – 7"
    peridot.transparency = "Opaque"
    peridot.timestamp = Date()

    let bismuth = Gem(context: viewContext)
    bismuth.name = "Bismuth"
    bismuth.info = """
    Bismuth is a gemstone with a metallic shine.
    It is element 83 on the periodic table.
    Bismuths excel at building structures and forging weapons.
    """
    bismuth.imageName = "bismuth"
    bismuth.mainColor = "metal"
    bismuth.crystalSystem = "n/a"
    bismuth.formula = "(Mg,Fe)₂SiO₄"
    bismuth.hardness = "2.25"
    bismuth.transparency = "n/a"
    bismuth.timestamp = Date()
  }
}
12. GemCommands.swift
import SwiftUI
import CoreData

struct GemCommands: Commands {
  var body: some Commands {
    CommandMenu("Gems") {
      Button(action: clearFavorites) {
        Label("Clear Favorites", systemImage: "trash")
      }
      .keyboardShortcut("C", modifiers: [.command, .shift])
    }
  }

  func clearFavorites() {
    let viewContext = PersistenceController.shared.container.viewContext
    let batchUpdateRequest = NSBatchUpdateRequest(entity: Gem.entity())
    batchUpdateRequest.propertiesToUpdate = ["favorite": false]
    do {
      try viewContext.execute(batchUpdateRequest)
    } catch {
      print("Handle Error: \(error.localizedDescription)")
    }
  }
}
13. AppMain.swift
import SwiftUI

@main
struct AppMain: App {
  let persistenceController = PersistenceController.shared
  var body: some Scene {
    WindowGroup {
      ContentView()
        .environment(\.managedObjectContext, persistenceController.container.viewContext)
    }
    .commands { GemCommands() }

    #if os(macOS)
    Settings {
      SettingsView()
    }
    #endif
  }
}
14. Persistence.swift
import CoreData

struct PersistenceController {
  static let shared = PersistenceController()

  let container: NSPersistentContainer

  init(inMemory: Bool = false) {
    container = NSPersistentContainer(name: "RayGem")
    if inMemory {
      container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores { _, error in
      if let error = error as NSError? {
        fatalError("Unresolved error \(error), \(error.userInfo)")
      }
    }

    if isFirstTimeLaunch && !inMemory {
      let viewContext = container.viewContext
      createInitialGems(viewContext: viewContext)

      do {
        try viewContext.save()
      } catch let dbError {
        let nsError = dbError as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
      }
    }
  }
}

// MARK: - First Time Launch
extension PersistenceController {
  var isFirstTimeLaunch: Bool {
    guard UserDefaults.standard.bool(forKey: "first_time_launch") else {
      UserDefaults.standard.setValue(true, forKey: "first_time_launch")
      return true
    }
    return false
  }
}

// MARK: - Preview data
extension PersistenceController {
  static var preview: PersistenceController = {
    let result = PersistenceController(inMemory: true)
    let viewContext = result.container.viewContext
    for index in 0...5 {
      let even = index % 2 == 0
      let gem = Gem(context: viewContext)
      gem.name = even ? "Lapis Lazuli" : "Rose Quartz"
      gem.info = even ? "Terraformer" : "The most sought-after crystal gems"
      gem.imageName = even ? "lapis" : "rose"
      gem.mainColor = even ? "blue" : "rose"
      gem.crystalSystem = "Hexagonal crystal system"
      gem.formula = "SiO₂"
      gem.hardness = "7"
      gem.transparency = "Translucent, Transparent"
      gem.timestamp = Date()
    }
    do {
      try viewContext.save()
    } catch {
      let nsError = error as NSError
      fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
    return result
  }()
}
15. GemListViewer.swift(iOS)
import SwiftUI

struct GemListViewer: View {
  var body: some View {
    TabView {
      NavigationView {
        GemList()
          .listStyle(InsetGroupedListStyle())
      }
      .tabItem {
        Label("All", systemImage: "list.bullet")
      }
      .tag(NavigationItem.all)

      NavigationView {
        FavoriteGems()
          .listStyle(InsetGroupedListStyle())
      }
      .tabItem {
        Label("Favorites", systemImage: "heart.fill")
      }
      .tag(NavigationItem.favorites)
    }
  }
}

struct GemListViewer_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      GemListViewer()

      GemListViewer()
        .previewDevice(PreviewDevice(rawValue: "iPad Air 2"))
    }
    .environment(
      \.managedObjectContext,
      PersistenceController.preview.container.viewContext)
  }
}
16. GemListViewer.swift(macOS)
import SwiftUI

struct GemListViewer: View {
  @State var selection: NavigationItem? = .all

  var sideBar: some View {
    List(selection: $selection) {
      NavigationLink(
        destination: GemList(),
        tag: NavigationItem.all,
        selection: $selection
      ) {
        Label("All", systemImage: "list.bullet")
      }
      .tag(NavigationItem.all)
      NavigationLink(
        destination: FavoriteGems(),
        tag: NavigationItem.favorites,
        selection: $selection
      ) {
        Label("Favorites", systemImage: "heart")
      }
      .tag(NavigationItem.favorites)
    }
    // 3
    .frame(minWidth: 200)
    .listStyle(SidebarListStyle())
    .toolbar {
      // 4
      ToolbarItem {
        Button(action: toggleSideBar) {
          Label("Toggle Sidebar", systemImage: "sidebar.left")
        }
      }
    }
  }

  var body: some View {
    NavigationView {
      sideBar
      Text("Select a category")
        .foregroundColor(.secondary)
      Text("Select a gem")
        .foregroundColor(.secondary)
    }
  }

  func toggleSideBar() {
    NSApp.keyWindow?.firstResponder?.tryToPerform(
      #selector(NSSplitViewController.toggleSidebar),
      with: nil)
  }
}

struct GemListViewer_Previews: PreviewProvider {
  static var previews: some View {
    GemListViewer()
      .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
  }
}

后记

本篇主要讲述了基于SwiftUI和Xcode12的Multiplatform App的搭建,感兴趣的给个赞或者关注~~~

上一篇下一篇

猜你喜欢

热点阅读