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阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353

推荐阅读更多精彩内容