SwiftUI框架詳細(xì)解析 (七) —— 基于SwiftUI的導(dǎo)航的實(shí)現(xiàn)(二)

版本記錄

版本號(hào) 時(shí)間
V1.0 2019.11.21 星期四

前言

今天翻閱蘋果的API文檔醒串,發(fā)現(xiàn)多了一個(gè)框架SwiftUI烦却,這里我們就一起來看一下這個(gè)框架宠叼。感興趣的看下面幾篇文章。
1. SwiftUI框架詳細(xì)解析 (一) —— 基本概覽(一)
2. SwiftUI框架詳細(xì)解析 (二) —— 基于SwiftUI的閃屏頁的創(chuàng)建(一)
3. SwiftUI框架詳細(xì)解析 (三) —— 基于SwiftUI的閃屏頁的創(chuàng)建(二)
4. SwiftUI框架詳細(xì)解析 (四) —— 使用SwiftUI進(jìn)行蘋果登錄(一)
5. SwiftUI框架詳細(xì)解析 (五) —— 使用SwiftUI進(jìn)行蘋果登錄(二)
6. SwiftUI框架詳細(xì)解析 (六) —— 基于SwiftUI的導(dǎo)航的實(shí)現(xiàn)(一)

源碼

1. Swift

首先看下代碼組織結(jié)構(gòu)

下面就是源碼了

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的導(dǎo)航的實(shí)現(xiàn)其爵,感興趣的給個(gè)贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末冒冬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子摩渺,更是在濱河造成了極大的恐慌简烤,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件摇幻,死亡現(xiàn)場(chǎng)離奇詭異横侦,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)绰姻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門枉侧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人狂芋,你說我怎么就攤上這事榨馁。” “怎么了帜矾?”我有些...
    開封第一講書人閱讀 152,671評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵翼虫,是天一觀的道長屑柔。 經(jīng)常有香客問我,道長珍剑,這世上最難降的妖魔是什么掸宛? 我笑而不...
    開封第一講書人閱讀 55,252評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮招拙,結(jié)果婚禮上旁涤,老公的妹妹穿的比我還像新娘。我一直安慰自己迫像,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評(píng)論 5 371
  • 文/花漫 我一把揭開白布瞳遍。 她就那樣靜靜地躺著闻妓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪掠械。 梳的紋絲不亂的頭發(fā)上由缆,一...
    開封第一講書人閱讀 49,031評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音猾蒂,去河邊找鬼均唉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛肚菠,可吹牛的內(nèi)容都是我干的舔箭。 我是一名探鬼主播,決...
    沈念sama閱讀 38,340評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼蚊逢,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼层扶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起烙荷,我...
    開封第一講書人閱讀 36,973評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤镜会,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后终抽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體戳表,經(jīng)...
    沈念sama閱讀 43,466評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評(píng)論 2 323
  • 正文 我和宋清朗相戀三年昼伴,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了匾旭。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,039評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡亩码,死狀恐怖季率,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情描沟,我是刑警寧澤飒泻,帶...
    沈念sama閱讀 33,701評(píng)論 4 323
  • 正文 年R本政府宣布鞭光,位于F島的核電站,受9級(jí)特大地震影響泞遗,放射性物質(zhì)發(fā)生泄漏惰许。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評(píng)論 3 307
  • 文/蒙蒙 一史辙、第九天 我趴在偏房一處隱蔽的房頂上張望汹买。 院中可真熱鬧,春花似錦聊倔、人聲如沸晦毙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽见妒。三九已至,卻和暖如春甸陌,著一層夾襖步出監(jiān)牢的瞬間须揣,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來泰國打工钱豁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留耻卡,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,497評(píng)論 2 354
  • 正文 我出身青樓牲尺,卻偏偏與公主長得像卵酪,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子秸谢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容