MapApp 地图应用

1. 简述

  1.1 重点

    1)更好地理解 MVVM 架构

    2)更轻松地使用 SwiftUI 框架、对齐、动画和转换

  1.2 资源下载地址:

Swiftful-Thinking:icon-default.png?t=N7T8https://www.swiftful-thinking.com/downloads

  1.3 项目结构图:

  1.4 图片、颜色资源文件图:

  1.5 启动图片配置图:

2. Model 层

  2.1 创建模拟位置文件 Location.swift

import Foundation
import MapKitstruct Location: Identifiable, Equatable{let name: Stringlet cityName: Stringlet coordinates: CLLocationCoordinate2Dlet description: Stringlet imageNames: [String]let link: String// UUID().uuidString,生产的每个ID都不一样,为了保证有相同可识别的相同模型,使用名称加城市名称var id: String {name + cityName}// Equatable 判断 id 是否一样static func == (lhs: Location, rhs: Location) -> Bool {return lhs.id == rhs.id}
}

3. 数据服务层

  3.1 创建模拟位置数据信息服务 LocationsDataSerVice.swift

import Foundation
import MapKitclass LocationsDataService {static let locations: [Location] = [Location(name: "Colosseum",cityName: "Rome",coordinates: CLLocationCoordinate2D(latitude: 41.8902, longitude: 12.4922),description: "The Colosseum is an oval amphitheatre in the centre of the city of Rome, Italy, just east of the Roman Forum. It is the largest ancient amphitheatre ever built, and is still the largest standing amphitheatre in the world today, despite its age.",imageNames: ["rome-colosseum-1","rome-colosseum-2","rome-colosseum-3",],link: "https://en.wikipedia.org/wiki/Colosseum"),Location(name: "Pantheon",cityName: "Rome",coordinates: CLLocationCoordinate2D(latitude: 41.8986, longitude: 12.4769),description: "The Pantheon is a former Roman temple and since the year 609 a Catholic church, in Rome, Italy, on the site of an earlier temple commissioned by Marcus Agrippa during the reign of Augustus.",imageNames: ["rome-pantheon-1","rome-pantheon-2","rome-pantheon-3",],link: "https://en.wikipedia.org/wiki/Pantheon,_Rome"),Location(name: "Trevi Fountain",cityName: "Rome",coordinates: CLLocationCoordinate2D(latitude: 41.9009, longitude: 12.4833),description: "The Trevi Fountain is a fountain in the Trevi district in Rome, Italy, designed by Italian architect Nicola Salvi and completed by Giuseppe Pannini and several others. Standing 26.3 metres high and 49.15 metres wide, it is the largest Baroque fountain in the city and one of the most famous fountains in the world.",imageNames: ["rome-trevifountain-1","rome-trevifountain-2","rome-trevifountain-3",],link: "https://en.wikipedia.org/wiki/Trevi_Fountain"),Location(name: "Eiffel Tower",cityName: "Paris",coordinates: CLLocationCoordinate2D(latitude: 48.8584, longitude: 2.2945),description: "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower. Locally nicknamed 'La dame de fer', it was constructed from 1887 to 1889 as the centerpiece of the 1889 World's Fair and was initially criticized by some of France's leading artists and intellectuals for its design, but it has become a global cultural icon of France and one of the most recognizable structures in the world.",imageNames: ["paris-eiffeltower-1","paris-eiffeltower-2",],link: "https://en.wikipedia.org/wiki/Eiffel_Tower"),Location(name: "Louvre Museum",cityName: "Paris",coordinates: CLLocationCoordinate2D(latitude: 48.8606, longitude: 2.3376),description: "The Louvre, or the Louvre Museum, is the world's most-visited museum and a historic monument in Paris, France. It is the home of some of the best-known works of art, including the Mona Lisa and the Venus de Milo. A central landmark of the city, it is located on the Right Bank of the Seine in the city's 1st arrondissement.",imageNames: ["paris-louvre-1","paris-louvre-2","paris-louvre-3",],link: "https://en.wikipedia.org/wiki/Louvre"),]
}

4. ViewModel 层

  4.1 创建位置信息的 ViewModel LocationsViewModel.swift

import Foundation
import MapKit
import SwiftUIclass LocationsViewModel: ObservableObject{/// All loaded locations Published@Published var locationes: [Location] = []/// Current location on map@Published var mapLocation: Location {didSet {// 设置地图位置,然后更新地图区域updateMapRegion(location: mapLocation)}}/// Current region on map :  这是地图上的当前区域@Published var mapRegion: MKCoordinateRegion = MKCoordinateRegion()/// 坐标跨度let mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)/// Show list of locations : 显示位置列表@Published var showLocationsList: Bool = false/// Show location detail via sheet : 显示位置详情信息页面@Published var sheetLocation: Location? = nilinit() {let locations = LocationsDataService.locationsself.locationes = locationsself.mapLocation = locations.first!self.updateMapRegion(location: locations.first!)}/// 更新地图区域private func updateMapRegion(location: Location){withAnimation(.easeInOut) {mapRegion = MKCoordinateRegion(// 中心点: 经纬度 latitude: 纬度  longitude: 经度center: location.coordinates,// 坐标跨度:span: mapSpan)}}/// 位置列表开关func toggleLocationsList(){withAnimation(.easeInOut) {// showLocationsList = !showLocationsListshowLocationsList.toggle()}}/// 显示下一个位置func showNextLocation(location: Location){withAnimation(.easeInOut) {mapLocation = locationshowLocationsList = false}}/// 下一个按钮处理事件func nextButtonPressed(){// Get the current indexguard let currentIndex = locationes.firstIndex(where: { $0 == mapLocation }) else {print("Could not find current index in locations array! Should naver happen.")return}// check if the nextIndex is valid: 检查下一个索引是否有校let nextIndex = currentIndex + 1guard locationes.indices.contains(nextIndex) else {// Next index is NOT avlid// Restart from 0guard let firstLocation = locationes.first else { return }showNextLocation(location: firstLocation)return}// Next index IS validlet nextLocation = locationes[nextIndex]showNextLocation(location: nextLocation)}
}

5. 创建 View 层

  5.1 位置列表 View

    1) 创建实现文件 LocationsListView.swift
import SwiftUI/// 位置列表
struct LocationsListView: View {/// 环境变量中的 ViewModel@EnvironmentObject private var viewMode: LocationsViewModelvar body: some View {List {ForEach(viewMode.locationes) { location inButton {viewMode.showNextLocation(location: location)} label: {listRowView(location: location)}.padding(.vertical, 4).listRowBackground(Color.clear)}}.listStyle(.plain)}
}extension LocationsListView {/// 列表行private func listRowView(location: Location) -> some View{HStack {if let imageName = location.imageNames.first {Image(imageName).resizable().scaledToFill().frame(width: 45, height: 45).cornerRadius(10)}VStack(alignment: .leading) {Text(location.name).font(.headline)Text(location.cityName).font(.headline)}.frame(maxWidth: .infinity, alignment: .leading)}}
}struct LocationsListView_Previews: PreviewProvider {static var previews: some View {LocationsListView().environmentObject(LocationsViewModel())}
}
    2) 效果图:

  5.2 位置预览 View

    1) 创建实现文件 LocationPreviewView.swift
import SwiftUI/// 位置预览视图
struct LocationPreviewView: View {/// 环境变量中配置的 viewModel@EnvironmentObject private var viewModel: LocationsViewModellet location: Locationvar body: some View {HStack(alignment:.bottom, spacing: 0) {VStack(alignment: .leading, spacing: 16) {imageSectiontitleSection}VStack(spacing: 8) {learnMoreButtonnextButton}}.padding(20).background(RoundedRectangle(cornerRadius: 10).fill(.ultraThinMaterial.opacity(0.7)).offset(y: 65)).cornerRadius(10)}
}extension LocationPreviewView {/// 图片部分private var imageSection: some View{ZStack {if let imageImage = location.imageNames.first{Image(imageImage).resizable().scaledToFill().frame(width: 100, height: 100).cornerRadius(10)}}.padding(6).background(Color.white).cornerRadius(10)}/// 标题部分private var titleSection: some View{VStack(alignment: .leading, spacing: 4) {Text(location.name).font(.title2).fontWeight(.bold)Text(location.cityName).font(.subheadline)}.frame(maxWidth: .infinity, alignment: .leading)}/// 了解更多按钮private var learnMoreButton: some View{Button {viewModel.sheetLocation = location} label: {Text("Learn more").font(.headline).frame(width: 125, height: 35)}.buttonStyle(.borderedProminent)}/// 下一个按钮private var nextButton: some View{Button {viewModel.nextButtonPressed()} label: {Text("Next").font(.headline).frame(width: 125, height: 35)}.buttonStyle(.bordered)}
}struct LocationPreviewView_Previews: PreviewProvider {static var previews: some View {ZStack {Color.black.ignoresSafeArea()LocationPreviewView(location: LocationsDataService.locations.first!).padding()}.environmentObject(LocationsViewModel())}
}
    2) 效果图:

  5.3 位置注释 View

    1) 创建实现文件 LocationMapAnnotationView.swift
import SwiftUI/// 位置注释视图
struct LocationMapAnnotationView: View {let accentColor = Color("AccentColor")var body: some View {VStack(spacing: 0) {Image(systemName: "map.circle.fill").resizable().scaledToFill().frame(width: 30, height: 30).font(.headline).foregroundColor(.white).padding(6).background(accentColor)//.cornerRadius(36).clipShape(Circle())Image(systemName: "triangle.fill").resizable().scaledToFill().foregroundColor(accentColor).frame(width: 10, height: 10).rotationEffect(Angle(degrees: 180)).offset(y: -3).padding(.bottom, 35)}}
}#Preview {ZStack{Color.black.ignoresSafeArea()LocationMapAnnotationView()}
}
    2) 效果图:

  5.4 主页 View

    1) 创建实现文件 LocationsView.swift
import SwiftUI
import MapKit/// 主页 View
struct LocationsView: View {@EnvironmentObject private var viewModel: LocationsViewModellet maxWidthForIpad: CGFloat = 700var body: some View {ZStack {mapLayer.ignoresSafeArea()VStack(spacing: 0) {header.padding().frame(maxWidth: maxWidthForIpad)Spacer()locationsPreviewStack}}// .fullScreenCover 全屏显示.sheet(item: $viewModel.sheetLocation) { location inLocationDetailView(location: location)}}
}extension LocationsView {/// 头Viewprivate var header: some View{VStack {Button {viewModel.toggleLocationsList()} label: {Text(viewModel.mapLocation.name + ", " + viewModel.mapLocation.cityName).font(.title2).fontWeight(.black).foregroundColor(.primary).frame(height: 55).frame(maxWidth: .infinity).animation(.none, value: viewModel.mapLocation).overlay(alignment: .leading) {Image(systemName: "arrow.down").font(.headline).foregroundColor(.primary).padding().rotationEffect(Angle(degrees: viewModel.showLocationsList ? 180 : 0))}}// 列表if viewModel.showLocationsList{LocationsListView()}}.background(.thickMaterial.opacity(0.7)).cornerRadius(10).shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 15)}/// 地图 Viewprivate var mapLayer: some View{Map(coordinateRegion: $viewModel.mapRegion,annotationItems: viewModel.locationes,annotationContent: { location in// 地图标识颜色// MapMarker(coordinate: location.coordinates, tint: .blue)// 自定义标识MapAnnotation(coordinate: location.coordinates) {LocationMapAnnotationView().scaleEffect(viewModel.mapLocation == location ? 1 : 0.7).shadow(radius: 10).onTapGesture {viewModel.showNextLocation(location: location)}}})}/// 地址预览堆栈private var locationsPreviewStack: some View{ZStack {ForEach(viewModel.locationes) { location in// 显示当前地址if viewModel.mapLocation == location {LocationPreviewView(location: location).shadow(color: Color.black.opacity(0.3), radius: 20).padding().frame(maxWidth: maxWidthForIpad).frame(maxWidth: .infinity)// .opacity// .transition(AnyTransition.scale.animation(.easeInOut))// 添加动画.transition(.asymmetric(insertion: .move(edge: .trailing),removal: .move(edge: .leading)))}}}}
}struct LocationsView_Previews: PreviewProvider {static var previews: some View {LocationsView().environmentObject(LocationsViewModel())}
}
    2) 效果图:

  5.5 位置详情页 View

    1) 创建实现文件 LocationDetailView.swift
import SwiftUI
import MapKit/// 位置详情页视图
struct LocationDetailView: View {// @Environment(\.presentationMode) var presentationMode// @Environment(\.dismiss) var dismiss@EnvironmentObject private var viewModel: LocationsViewModellet location: Locationvar body: some View {ScrollView {VStack {imageSectionVStack(alignment: .leading, spacing: 16){titleSectionDivider()descriptionSectionDivider()mapLayer}.frame(maxWidth: .infinity, alignment: .leading).padding()}}// 安全区.ignoresSafeArea()// 超薄材质,灰白色.background(.ultraThinMaterial)// 添加返回按钮.overlay(alignment: .topLeading) {backButton}}
}extension LocationDetailView{/// 滑动切换图private var imageSection: some View{TabView {ForEach(location.imageNames, id: \.self) {Image($0).resizable().scaledToFill().frame(width: UIDevice.current.userInterfaceIdiom == .pad  ? nil : UIScreen.main.bounds.width).clipped()}}.frame(height: 500).tabViewStyle(.page).shadow(color: .black.opacity(0.3), radius: 20, y: 10)}/// 标题视图private var titleSection: some View{VStack(alignment: .leading, spacing: 8){Text(location.name).font(.largeTitle).fontWeight(.semibold).foregroundStyle(.primary)Text(location.cityName).font(.title3).foregroundStyle(.secondary)}}/// 描述视图private var descriptionSection: some View{VStack(alignment: .leading, spacing: 16){Text(location.description).font(.subheadline).foregroundStyle(.secondary)if let url = URL(string: location.link) {Link("Read more on Wikipedia", destination: url).font(.headline).tint(.blue)}}}/// 地图 Viewprivate var mapLayer: some View{Map(coordinateRegion: .constant(MKCoordinateRegion(center: location.coordinates,span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))),annotationItems: [location]) { location inMapAnnotation(coordinate: location.coordinates){// 自定义标识LocationMapAnnotationView().shadow(radius: 10)}}.allowsHitTesting(false) // 禁止点击.aspectRatio(1, contentMode: .fit) // 纵横比.cornerRadius(30)}/// 返回按钮private var backButton: some View{Button{// dismiss.callAsFunction()viewModel.sheetLocation = nil} label: {Image(systemName: "xmark").font(.headline).padding(16).foregroundColor(.primary).background(.thickMaterial).cornerRadius(10).shadow(radius: 4).padding()}}
}#Preview {LocationDetailView(location: LocationsDataService.locations.first!).environmentObject(LocationsViewModel())
}
    2) 效果图:

  5.6 启动结构体文件 SwiftfulMapAppApp.swift

import SwiftUI@main
struct SwiftfulMapAppApp: App {@StateObject private var viewModel = LocationsViewModel()var body: some Scene {WindowGroup {LocationsView().environmentObject(viewModel)}}
}

6. 整体效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/194536.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux | 安装openGauss数据库

Linux 安装openGauss数据库 今天我们来安装一下国产数据库openGauss~~ 下载openGauss 首先在官网:https://opengauss.org/zh/download/下载对应的安装包,我们这里下载LInux 极简版来演示安装 下载后,使用root用户上传到Linux ,这边上传到/usr/local/目录下, 使用…

IoC和DI

Spring 是包含众多工具的 IoC 容器,存的是对象,对象这个词在 Spring 的范围内,称之为 bean IoC 是控制反转 控制权进行了反转,比如对某一个东西的控制权在 A 手上,结果变成了 B ,Spring 管理的是 bean ,所以这里的控制权指的是 bean 的控制权,也就是对象的控制权进行了反转 …

SAP PI/PO中使用UDF解决按字节拆分字符串的需求

需求背景: SAP需要将采购订单信息通过PI发送到SFTP服务器上,生成文件,一般对日项目上文件内容通常都是按照指定的字节数拆分的,而不是字符数,类似下面的格式。 问题点: 如果是使用FTP适配器,则…

MySQL JDBC编程

MySQL JDBC编程 文章目录 MySQL JDBC编程1. 数据库编程的必备条件2. Java的数据库编程:JDBC3. JDBC工作原理4. JDBC使用5. JDBC常用接口和类5.1 JDBC API5.2 数据库连接Connection5.3 Statement对象5.4 ResultSet对象 1. 数据库编程的必备条件 编程语言:…

[PyTorch][chapter 63][强化学习-时序差分学习]

目录: 蒙特卡罗强化学习的问题 基于转移的策略评估 时序差分评估 Sarsa-算法 Q-学习算法 一 蒙特卡罗强化学习的的问题 有模型学习: Bellman 等式 免模型学习: 蒙特卡罗强化学习 迭代: 使用策略 生成一个轨迹, for t…

京联易捷科技与劳埃德私募基金管理有限公司达成合作协议签署

京联易捷科技与劳埃德私募基金管理有限公司今日宣布正式签署合作协议,双方在数字化进程、资产管理与投资以及中英金融合作方面将展开全面合作。 劳埃德(中国)私募基金管理有限公司是英国劳埃德私募基金管理有限公司的全资子公司,拥有丰富的跨境投资经验和卓越的募资能力。该集…

LEEDCODE 220 存在重复元素3

class Solution { public:int getId(int a, int valuediff){// 值// return a/(valuediff1);return a < 0 ? (a ) -) / (valuediff 1) - 1 : a / (valuediff 1);}public: unordered_map<int, int> bucket;bool containsNearbyAlmostDuplicate(vector<int>&am…

【Java实现图书管理系统】

图书管理系统 1. 设计背景2. 设计思路3. 模块展示代码演示3.1 Book类3.2 BookList类&#xff08;书架类&#xff09;3.4 用户类 - User类3.5 子类管理员类 -- AdminUser类3.6 子类普通用户类 -- NormalUser类3.7 操作接口3.8 操作类3.8.1 查找操作 -- FindOperation类3.8.2 增加…

【excel技巧】Excel表格里的图片如何批量调整大小?

Excel表格里面插入了很多图片&#xff0c;但是每张图片大小不一&#xff0c;如何做到每张图片都完美的与单元格大小相同&#xff1f;并且能够根据单元格来改变大小&#xff1f;今天分享&#xff0c;excel表格里的图片如何批量调整大小。 方法如下&#xff1a; 点击表格中的一…

VBA技术资料MF83:将Word文档批量另存为PDF文件

我给VBA的定义&#xff1a;VBA是个人小型自动化处理的有效工具。利用好了&#xff0c;可以大大提高自己的工作效率&#xff0c;而且可以提高数据的准确度。我的教程一共九套&#xff0c;分为初级、中级、高级三大部分。是对VBA的系统讲解&#xff0c;从简单的入门&#xff0c;到…

JS原生-弹框+阿里巴巴矢量图

效果&#xff1a; 代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content&q…

Linux_系统信息_uname查看内核版本、内核建立时间、处理器类型、顺便得到操作系统位数等

1、uname --help 使用uname --help查看uname命令的帮助信息 2、uname -a 通过上面的help就知道-a选项显示全部内容时的含义了。 内核名是Linux主机名是lubancat&#xff0c;如果想看主机名可以使用命令hostname&#xff1b;内核版本是Linux 4.19.232&#xff0c;建立时间为2…

NewStarCTF2023 Reverse方向Week3 ez_chal WP

分析 题目&#xff1a;ez_chal 一个XTEA加密&#xff0c; V6是key&#xff0c;v5是输入&#xff0c;然后v7就是密文。 看了v6&#xff0c;要用动调。 ELF文件用ida的远程调试。 然后在kali上输入长度为32的flag 全部转换成dd 再提取密文。 EXP #include <stdio.h>…

使用Spring Boot实现大文件断点续传及文件校验

一、简介 随着互联网的快速发展&#xff0c;大文件的传输成为了互联网应用的重要组成部分。然而&#xff0c;由于网络不稳定等因素的影响&#xff0c;大文件的传输经常会出现中断的情况&#xff0c;这时需要重新传输&#xff0c;导致传输效率低下。 为了解决这个问题&#xff…

OpenCV中的像素重映射原理及实战分析

引言 映射是个数学术语&#xff0c;指两个元素的集之间元素相互“对应”的关系&#xff0c;为名词。映射&#xff0c;或者射影&#xff0c;在数学及相关的领域经常等同于函数。 基于此&#xff0c;部分映射就相当于部分函数&#xff0c;而完全映射相当于完全函数。 说的简单点…

2.FastRunner定时任务Celery+RabbitMQ

注意&#xff1a;celery版本和Python冲突问题 不能用高版本Python 用3.5以下&#xff0c;因为项目的celery用的django-celery 3.2.2 python3.7 async关键字 冲突版本 celery3.x方案一&#xff1a; celery3.xpython3.6方案二 &#xff1a; celery4.xpython3.7 解决celery执…

海康Visionmaster-环境配置:VB.Net 二次开发环境配 置方法

Visual Basic 进行 VM 二次开发的环境配置分为三步。 第一步&#xff0c;使用 VS 新建一个框架为.NET Framework 4.6.1&#xff0c;平台去勾选首选 32 为的工程&#xff0c;重新生成解决方案&#xff0c;保证工程 Debug 下存在 exe 文件&#xff0c;最后关闭新建工程&#xff1…

2024有哪些免费的mac苹果电脑内存清理工具?

在我们日常使用苹果电脑的过程中&#xff0c;随着时间的推移&#xff0c;可能会发现设备的速度变慢了&#xff0c;甚至出现卡顿的现象。其中一个常见的原因就是程序占用内存过多&#xff0c;导致系统无法高效地运行。那么&#xff0c;苹果电脑内存怎么清理呢&#xff1f;本文将…

Linux动静态库

文章目录 1. 静态库2. 动态库3. 动态库的加载 本章代码gitee仓库&#xff1a;动静态库 1. 静态库 Linux开发工具gcc/g篇&#xff0c;此篇文章讲过动静态库的基本概念&#xff0c;不了解的可以先看一下这篇文章。 现在我们先来制作一个简单的静态库 mymath.h #pragma once#i…

Jmeter- Beanshell语法和常用内置对象(网络整理)

在利用jmeter进行接口测试或者性能测试的时候&#xff0c;我们需要处理一些复杂的请求&#xff0c;此时就需要利用beanshell脚本了&#xff0c;BeanShell是一种完全符合Java语法规范的脚本语言,并且又拥有自己的一些语法和方法&#xff0c;所以它和java是可以无缝衔接的。beans…