SwiftUI框架詳細解析 (七) —— 基于SwiftUI的導航的實現(二)

版本記錄

版本號 時間
V1.0 2019.11.21 星期四

前言

今天翻閱蘋果的API文檔,發現多了一個框架SwiftUI,這里我們就一起來看一下這個框架。感興趣的看下面幾篇文章。
1. SwiftUI框架詳細解析 (一) —— 基本概覽(一)
2. SwiftUI框架詳細解析 (二) —— 基于SwiftUI的閃屏頁的創建(一)
3. SwiftUI框架詳細解析 (三) —— 基于SwiftUI的閃屏頁的創建(二)
4. SwiftUI框架詳細解析 (四) —— 使用SwiftUI進行蘋果登錄(一)
5. SwiftUI框架詳細解析 (五) —— 使用SwiftUI進行蘋果登錄(二)
6. SwiftUI框架詳細解析 (六) —— 基于SwiftUI的導航的實現(一)

源碼

1. Swift

首先看下代碼組織結構

下面就是源碼了

1. SceneDelegate.swift
import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  var window: UIWindow?

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
//    let contentView = ArtTabView()

    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
    }
  }
}
2. ContentView.swift
import SwiftUI

struct ContentView: View {
//  let disciplines = ["statue", "mural", "plaque", "statue"]
  @State var artworks = artData
  @State private var hideVisited = false
  
  var showArt: [Artwork] {
    hideVisited ? artworks.filter { $0.reaction == "" } : artworks
  }

  private func setReaction(_ reaction: String, for item: Artwork) {
    if let index = artworks.firstIndex(
      where: { $0.id == item.id }) {
      artworks[index].reaction = reaction
    }
  }

  var body: some View {
    NavigationView {
      List(showArt) { artwork in
        NavigationLink(
        destination: DetailView(artwork: artwork)) {
          Text("\(artwork.reaction)  \(artwork.title)")
            .onAppear() { artwork.load() }
            .contextMenu {
              Button("Love it: ??") {
                self.setReaction("??", for: artwork)
              }
              Button("Thoughtful: ??") {
                self.setReaction("??", for: artwork)
              }
              Button("Wow!: ??") {
                self.setReaction("??", for: artwork)
              }
          }
        }
      }
      .navigationBarTitle("Artworks")
      .navigationBarItems(trailing:
        Toggle(isOn: $hideVisited, label: { Text("Hide Visited") }))
      
      DetailView(artwork: artworks[0])
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
3. ArtTabView.swift
import SwiftUI

struct ArtTabView: View {
  @State var artworks = artData
  
  var body: some View {
    TabView {
      NavigationView {
        ArtList(artworks: $artworks, tabTitle: "All Artworks", hideVisited: false)
        DetailView(artwork: artworks[0])
      }
      .tabItem({
        Text("Artworks ?? ?? ??")
      })
      
      NavigationView {
        ArtList(artworks: $artworks, tabTitle: "Unvisited Artworks", hideVisited: true)
        DetailView(artwork: artworks[0])
      }
      .tabItem({ Text("Unvisited Artworks") })
    }
  }
}

struct ArtTabView_Previews: PreviewProvider {
  static var previews: some View {
    ArtTabView()
  }
}

struct ArtList: View {
  @Binding var artworks: [Artwork]
  let tabTitle: String
  let hideVisited: Bool
  
  var showArt: [Artwork] {
    hideVisited ? artworks.filter { $0.reaction == "" } : artworks
  }
  
  private func setReaction(_ reaction: String, for item: Artwork) {
    if let index = artworks.firstIndex(
      where: { $0.id == item.id }) {
      artworks[index].reaction = reaction
    }
  }
  
  var body: some View {
    List(showArt) { artwork in
      NavigationLink(
      destination: DetailView(artwork: artwork)) {
        Text("\(artwork.reaction)  \(artwork.title)")
          .onAppear() { artwork.load() }
          .contextMenu {
            Button("Love it: ??") {
              self.setReaction("??", for: artwork)
            }
            Button("Thoughtful: ??") {
              self.setReaction("??", for: artwork)
            }
            Button("Wow!: ??") {
              self.setReaction("??", for: artwork)
            }
        }
      }
    }
    .navigationBarTitle(tabTitle)
  }
}
4. DetailView.swift
import SwiftUI

struct DetailView: View {
  let artwork: Artwork
  @State private var showMap = false

  var body: some View {
    VStack {
      Image(artwork.imageName)
        .resizable()
        .frame(maxWidth: 300, maxHeight: 600)
        .aspectRatio(contentMode: .fit)
      Text("\(artwork.reaction)  \(artwork.title)")
        .font(.headline)
        .multilineTextAlignment(.center)
        .lineLimit(3)
      HStack {
        Button(action: { self.showMap = true }) {
          Image(systemName: "mappin.and.ellipse")
        }
        .sheet(isPresented: $showMap) {
//          MapView(coordinate: self.artwork.coordinate)
          LocationMap(showModal: self.$showMap, artwork: self.artwork)
        }
        Text(artwork.locationName)
          .font(.subheadline)
      }
      Text("Artist: \(artwork.artist)")
        .font(.subheadline)
      Divider()
      Text(artwork.description)
        .multilineTextAlignment(.leading)
        .lineLimit(20)
    }
    .padding()
    .navigationBarTitle(Text(artwork.title), displayMode: .inline)
  }
}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
      DetailView(artwork: artData[0])
    }
}
5. LocationMap.swift
import SwiftUI

struct LocationMap: View {
  @Binding var showModal: Bool
  var artwork: Artwork

  var body: some View {
    VStack {
      MapView(coordinate: artwork.coordinate)
      HStack {
        Text(self.artwork.locationName)
        Spacer()
        Button("Done") { self.showModal = false }
      }
      .padding()
    }
  }
}

struct LocationMap_Previews: PreviewProvider {
  static var previews: some View {
    LocationMap(showModal: .constant(true), artwork: artData[0])
  }
}
6. MapView.swift
import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {
  var coordinate: CLLocationCoordinate2D

  func makeUIView(context: Context) -> MKMapView {
    MKMapView(frame: .zero)
  }

  func updateUIView(_ view: MKMapView, context: Context) {
    let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
    let region = MKCoordinateRegion(center: coordinate, span: span)

    // Added annotation for PublicArt project
    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    view.addAnnotation(annotation)

    view.setRegion(region, animated: true)
  }
}

struct MapView_Previews: PreviewProvider {
  static var previews: some View {
    // Using Artwork object instead of Landmark
    MapView(coordinate: artData[5].coordinate)
  }
}
7. Artwork.swift
import MapKit
import SwiftUI

struct Artwork {
  let id = UUID()
  let artist: String
  let description: String
  let locationName: String
  let discipline: String
  let title: String
  let imageName: String
  let coordinate: CLLocationCoordinate2D
  var reaction: String

  func load() {
    print(">>>>> Downloading \(self.imageName) <<<<<")
  }

//  init(artist: String, description: String, locationName: String, discipline: String,
//       title: String, imageName: String, coordinate: CLLocationCoordinate2D, reaction: String) {
//    print(">>>>> Downloading \(imageName) <<<<<")
//    self.artist = artist
//    self.description = description
//    self.locationName = locationName
//    self.discipline = discipline
//    self.title = title
//    self.imageName = imageName
//    self.coordinate = coordinate
//    self.reaction = reaction
//  }
}

extension Artwork: Identifiable { }

// Subset of Honolulu Public Art data set at
// https://data.honolulu.gov/dataset/Public-Art/yef5-h88r
// Note: The current imagefile server is different from what's listed.
// Current URLs are in image-urls.txt in the starter folder.

let artData = [
  Artwork(artist: "Sean Browne", description: "Bronze figure of Prince Jonah Kuhio Kalanianaole", locationName: "Kuhio Beach", discipline: "Sculpture", title: "Prince Jonah Kuhio Kalanianaole", imageName: "002_200105", coordinate: CLLocationCoordinate2D(latitude: 21.273389, longitude: -157.823802), reaction: ""),
  Artwork(artist: "Robert Lee Eskridge", description: "One of a pair of murals at Ala Mona Regional Park. A Works Progress Administration art project, done in the Art Deco style. It depicts various aspects of makahiki (harvest festival), imagined as taking place in the vicinity of what is now known as Ala Moana Park, makahiki pa'ani ho'oikaika (annual sports tournaments) are emphasized. This mural depicts ali'i with their retainers traveling between villages by wa'a kaulua (double hulled canoe), a carving of Lono and kahili (feather standards) accompany them. Puowaina (Punchbowl) is shown in the background. Also depicted is he'e nalu (surfing) on olo (long surfboard) and 'o'o ihe (sport of spear throwing) whereby a group of men, at a given signal, hurl their spears at one man who would either catch the spears, dodge them, or otherwise fend them off.", locationName: "Lester McCoy Pavilion", discipline: "Mural", title: "Makahiki Festival Mauka Mural", imageName: "19300102", coordinate: CLLocationCoordinate2D(latitude: 21.290959, longitude: -157.851265), reaction: ""),
  Artwork(artist: "Kate Kelly", description: "A cast bronze commemorative plaque set into a monolith. The plaque memorializes Amelia Earhart's first flight to Hawaii in 1935.", locationName: "Diamond Head Lookout/Kuilei Beach Cliffs", discipline: "Plaque", title: "Amelia Earhart Memorial Plaque", imageName: "193701", coordinate: CLLocationCoordinate2D(latitude: 21.256139, longitude: -157.804769), reaction: "??"),
  Artwork(artist: "Marguerite Louis Blasingame", description: "The stone bas relief entry way to the 1939 Board of Water Supply building. The bas relief is executed on a series of green steatite stone blocks which depict mythical and human Hawaiian figures, flora, and animals in the upper portions flanking either side of a central doorway as well as stylized letter forming a narrative text beneath the figurative panels. The two panels, one on the Diamond Head side of the entry way and the other on the other side of the entry door both depict stories involving the god Kane and Kaneloa in a mythical story about the discovery and use of water.", locationName: "Board of Water Supply Engineering Building Entrance", discipline: "Mural", title: "Ka Wai Ake Akua", imageName: "193901-5", coordinate: CLLocationCoordinate2D(latitude: 21.306108, longitude: -157.852555), reaction: ""),
  Artwork(artist: "Juliette May Fraser", description: "A mural depicting various agricultural activities occurring in Hawaii over several time periods, from pre-contact to the 20th century.", locationName: "Board of Water Supply Building Lobby", discipline: "Mural", title: "Pure Water: Man's Greatest Need", imageName: "195801", coordinate: CLLocationCoordinate2D(latitude: 21.306008, longitude: -157.853896), reaction: ""),
  Artwork(artist: "Charles Watson", description: "A stylized sculpture of a giraffe with the body made of welded rebar rings. The body is articulated by using weld material to give the spotty look of the animal. The head is approximately 12\" long and it peers down, its mouth open, and with long eyelashes. There are ears and horns on its head and there are iron rods of about 4-6\" in length that are used to articulate the hairs on the back of the giraffe's neck.", locationName: "Honolulu Zoo Elephant Exhibit", discipline: "Sculpture", title: "Giraffe", imageName: "198912", coordinate: CLLocationCoordinate2D(latitude: 21.270449, longitude: -157.819816), reaction: ""),
  Artwork(artist: "Yoshinari Kochi", description: "A roughly carved \"C\" form which represents \"century,\" supported by a pillar with four Chinese characters on the sides which signify that \"blessings from heaven are invoked by peace and harmony.\" The sculpture commemorates the 75th anniversary of the first Japanese immigrants to arrive in Hawaii.", locationName: "Foster Botanical Garden", discipline: "Sculpture", title: "Hiroshima Monument", imageName: "196001", coordinate: CLLocationCoordinate2D(latitude: 21.316633, longitude: -157.858247), reaction: "??"),
  Artwork(artist: "Unknown", description: "Bronze plaque mounted on a stone with an inscription marking the site of an artesian well.", locationName: "1922 Wilder Avenue", discipline: "Plaque", title: "Pioneer Artesian Well Site", imageName: "193301-2", coordinate: CLLocationCoordinate2D(latitude: 21.30006, longitude: -157.827969), reaction: ""),
  Artwork(artist: "Unknown", description: "Bronze \"Roll of Honor\" plaque listing 101 Hawaii citizens killed in World War I.", locationName: "Queen's Beach", discipline: "Plaque", title: "Roll of Honor", imageName: "193101", coordinate: CLLocationCoordinate2D(latitude: 21.26466, longitude: -157.821463), reaction: ""),
  Artwork(artist: "Unknown", description: "Bronze plaque honoring Don Francisco de Paula Marin.", locationName: "Marin Tower Courtyard", discipline: "Plaque", title: "Francisco De Paula Marin Residence", imageName: "199909", coordinate: CLLocationCoordinate2D(latitude: 21.311242, longitude: -157.864106), reaction: ""),
  Artwork(artist: "Sean Browne", description: "Larger than life-size bronze figure of King David Kalakaua mounted on a granite pedestal.", locationName: "Waikiki Gateway Park", discipline: "Sculpture", title: "King David Kalakaua", imageName: "199103-3", coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661), reaction: "??"),
  Artwork(artist: "I-Fan Chen", description: "Standing bronze figure of Dr. Sun Yat Sen installed on a pedestal.", locationName: "Sun Yat-Sen Mall", discipline: "Sculpture", title: "Sun Yat Sen", imageName: "197613-5", coordinate: CLLocationCoordinate2D(latitude: 21.314309, longitude: -157.861825), reaction: "??"),
  Artwork(artist: "Emiko Mizutani", description: "Mural of white glazed and semi-glazed ceramic tiles mounted on wood panels.", locationName: "Pali Golf Course Clubhouse Ballroom Entry", discipline: "Mural", title: "Trees", imageName: "199802", coordinate: CLLocationCoordinate2D(latitude: 21.37307, longitude: -157.785564), reaction: "??"),
  Artwork(artist: "Don Dugal", description: "A painted wall relief consisting of over 200 small painted panels affixed to a wall depicting a view of the ocean and horizon beyond tree trunks and branches done in subtle gray and blue tones.", locationName: "Medical Examiner Facility Entry", discipline: "Mural", title: "November Light", imageName: "198803", coordinate: CLLocationCoordinate2D(latitude: 21.315893, longitude: -157.867302), reaction: "??"),
  Artwork(artist: "Elizabeth Mapelli", description: "A mosaic depicting tropical foliage against a starry sky.", locationName: "Alapai Police Station 1st Floor Entrance", discipline: "Mural", title: "Aloha Grotto", imageName: "199303-2", coordinate: CLLocationCoordinate2D(latitude: 21.304271, longitude: -157.851326), reaction: ""),
  Artwork(artist: "Marguerite Louis Blasingame", description: "One of a pair of low-relief marble tablets of a Hawaiian couple set into a wall.", locationName: "Lester McCoy Pavilion Banyan Court Garden", discipline: "Mural", title: "Hawaiian Couple", imageName: "19350202a", coordinate: CLLocationCoordinate2D(latitude: 21.291074, longitude: -157.851148), reaction: ""),
  Artwork(artist: "Paul Saviskas", description: "A stainless steel sculpture of three kihi kihi (Moorish idol fish) swimming around coral mounted on a concrete base.", locationName: "Hanauma Bay Visitor Center", discipline: "Sculpture", title: "Kihi Kihi", imageName: "200304", coordinate: CLLocationCoordinate2D(latitude: 21.273274, longitude: -157.694828), reaction: "??")
]

后記

本篇主要講述了基于SwiftUI的導航的實現,感興趣的給個贊或者關注~~~

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容