SwiftUI 内功:“曳光弹“实现自定义样式进度条(ProgressView)

本文主要是介绍SwiftUI 内功:“曳光弹“实现自定义样式进度条(ProgressView),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

概览

虽然 SwiftUI 已为我们内置了很多常用视图,不过有时我们还是需要根据实际来进一步美化显示或增加功能。

在这里插入图片描述

如上图所示,在本篇博文中我们将结合敏捷哲学中一个超级实用的开发技巧:曳光弹,来一步一个脚印循序渐进的实现 ProgressView 自定义显示效果。

相信看文本后,小伙伴的武器库中又会多了一件非常犀利的神兵利器!

Let’s go!!!😉


本文对应的视频课程请小伙伴们移步如下链接观赏:

  • SwiftUI 内功:“曳光弹“实现自定义进度条样式

从 ProgressViewStyle 开始

在 SwiftUI 中,大多数视图都暴露出对应的 style (以协议的方式)供我们定制它们的外观,比如 Button 的 ButtonStyle。

ProgressView 同样不例外,我们可以通过实现自己的 ProgressViewStyle 样式来完成其外观的美化。

/// A type that applies standard interaction behavior to all progress views
/// within a view hierarchy.
///
/// To configure the current progress view style for a view hierarchy, use the
/// ``View/progressViewStyle(_:)`` modifier.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public protocol ProgressViewStyle {/// A view representing the body of a progress view.associatedtype Body : View/// Creates a view representing the body of a progress view.////// - Parameter configuration: The properties of the progress view being///   created.////// The view hierarchy calls this method for each progress view where this/// style is the current progress view style.////// - Parameter configuration: The properties of the progress view, such as///  its preferred progress type.@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body/// A type alias for the properties of a progress view instance.typealias Configuration = ProgressViewStyleConfiguration
}

在这里,就让我们创建一个新的 IndicatorProgressViewStyle 样式来施展我们的拳脚吧!

曳光弹(Tracer)原则

在复杂项目开发中,我们一般做不到(或很难做到)一步到位。在敏捷开发哲学中有一个非常实用的秘技,我们称之为:曳(ye)光弹(或拽光弹)!

使用它我们可以由易而难,有条不紊的完成复杂目标。

在这里插入图片描述


关于曳光弹的详细介绍,请小伙伴们移步如下链接观赏:

  • 拽光弹?曳光弹?到底是哪个?为什么能发光,不怕暴露自己吗?

简单来说:我们的开发也要像曳光弹那样不求一发入魂,而是希望通过观察弹道(曳光弹晚上发射时其尾部会拖一道长长的光迹,像彗星美丽的尾部)不断调整射击位置,迭代进步,不断接近目标,最终“征服”目标!

曳光弹的诀窍是,每次只向着目标迈一小步,最终完成一大步!

第一次”射击“

我们的任务是完成如下 ProgressView 样式:

在这里插入图片描述


更详细的介绍,请移步如下链接进一步了解:

  • Working with ProgressView and ProgressViewStyle in SwiftUI

首先,我们先尝试搭建基本布局,当然一切都是静态的:

struct IndicatorProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {VStack {Text("30%")ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5))Capsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: 100)}.frame(height: 20)Text("Downloading...")}}
}

应用 IndicatorProgressViewStyle 样式很容易:

struct ContentView: View {@State var value = 0.3var body: some View {NavigationStack {VStack {ProgressView(value: value).progressViewStyle(IndicatorProgressViewStyle())}.padding()}}
}

运行效果如下:

在这里插入图片描述

我们第一发曳光弹已经射出,虽然离命中目标还差的很远,但我们起码得到了反馈,看到了希望!

希望就是正能量,希望就是黎明黑暗前那一丝曙光!!!

循序渐进

我们必须想方设法取得进度条的总长度,因为我们需要:

  1. 绘制当前进度对应进度条的长度;
  2. 让顶部指示器始终指向当前进度对应的位置;

有很多种方法可以达到该目的,这里我们选择一种最简单的方法:GeometryReader。

struct IndicatorProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {Text("\(String(format: "%.0f%%", progress * 100))")ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5)).overlay (GeometryReader { geo inCapsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: geo.size.width * progress, height: 20)})}.frame(height: 20)Text("Downloading...")}}
}

现在我们的进度条不再是静如处子,而是动如脱兔啦:

在这里插入图片描述

按部就班

接下来,我们再让进度条顶部指示器位置“动”起来。因为它的位置也和当前进度值有着藕断丝连的关系,所以有必要把它也放到 GeometryReader 内部去:

struct IndicatorProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5)).overlay (GeometryReader { geo inZStack(alignment: .topLeading) {VStack {Text("\(String(format: "%.0f%%", progress * 100))")Image(systemName: "arrowtriangle.down.fill")}.offset(x: 100, y: -40)Capsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: geo.size.width * progress, height: 20)}})}.frame(height: 20)Text("Downloading...")}}
}

在这里插入图片描述

效果如上,随着打出越来越多的曳光弹,我们也越来越接近最终目标!

随后,我们来修正指示器的位置:

struct IndicatorProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5)).overlay (GeometryReader { geo inZStack(alignment: .topLeading) {VStack {Text("\(String(format: "%.0f%%", progress * 100))")Image(systemName: "arrowtriangle.down.fill")}.frame(width: 40).offset(x: geo.size.width * progress - 20, y: -40)Capsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: geo.size.width * progress, height: 20)}})}.frame(height: 20)Text("Downloading...")}}
}

现在,我们的指示器也能够跟随进度条一起“如影随形”的移动啦:

在这里插入图片描述

一个小问题

不知细心的小伙伴们发现了吗?目前的实现有点小缺陷:当进度位于开始位置时,进度条显示的高度不太对:
在这里插入图片描述

这是因为我们的进度条是用 Capsule 形状来绘制的,而 Capsule 在宽度很窄时显示会趋于一个矩形,而且它被绘制在进度槽的外部。

如何解决呢?很简单,我们只需将进度条绘制限制在指定的 Capsule 内部就可以了:

struct IndicatorProgressViewStyle: ProgressViewStyle {func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {ZStack(alignment: .topLeading) {// 原代码从略...}.frame(height: 20)// 限制进度条在指定形状中显示.clipShape(Capsule(style: .continuous))Text("Downloading...")}}
}

在这里插入图片描述

效果好多了!

不过将进度条限制为指定形状,意味着其它部分(比如指示器)都会被裁剪掉,这可不是我们想要的。

随着更多曳光弹的射出,我们也对如何解决这一问题有了更多的线索,只需调整进度条指示器的位置即可:

struct IndicatorProgressViewStyle: ProgressViewStyle {private let labelWidth = 40.0private let viewHeight = 20.0func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {Capsule(style: .continuous).opacity(0.0).overlay {GeometryReader { geo inVStack {VStack {Text("\(String(format: "%.0f%%", progress * 100))")Image(systemName: "arrowtriangle.down.fill")}.font(.headline).frame(width: labelWidth).offset(x: progress * geo.size.width - labelWidth / 2, y: -40)}ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5))Capsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: progress * geo.size.width)}.clipShape(Capsule(style: .continuous))}}.frame(height: viewHeight)Text("Downloading...")}}
}

看看效果吧,我们已经快逼近最终目标了!

在这里插入图片描述

增加更多的定制项

现在,我们自定义进度条样式对于顶部指示器和底部描述的显示有着自己的“想法”,能不提供更多的自由让使用者决定如何显示呢?

答案是肯定的!

在 ProgressView 构造器中包含 label 和 currentValueLabel 可选参数,我可以用它们来决定进度条指示器和描述如何显示!

struct IndicatorProgressViewStyle: ProgressViewStyle {private let labelWidth = 40.0private let viewHeight = 20.0func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {Capsule(style: .continuous).opacity(0.0).overlay {GeometryReader { geo inVStack {VStack {if let curLabel = configuration.currentValueLabel {curLabel}else{Text("\(String(format: "%.0f%%", progress * 100))")}Image(systemName: "arrowtriangle.down.fill")}.frame(width: labelWidth).offset(x: progress * geo.size.width - labelWidth / 2, y: -40)}ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(.gray.opacity(0.5))Capsule(style: .continuous).foregroundStyle(.teal.gradient).frame(width: progress * geo.size.width)}.clipShape(Capsule(style: .continuous))}}.frame(height: viewHeight)configuration.label}}
}

至此,我们可以自由定制 ProgressView 的显示外观啦:

ProgressView(value: value, label: {Text(progressDetails).font(.title3.weight(.bold)).foregroundStyle(.green.gradient)
}, currentValueLabel: {Text("\(String(format: "🚴🏻‍♂️%.0f%%", value * 100))").font(.headline).frame(width: 60).foregroundStyle(Color.orange.gradient)
})
.progressViewStyle(IndicatorProgressViewStyle(color: AnyShapeStyle(.pink.gradient)))
.frame(width: 300)

让我们看一下美美哒的最终效果吧:

在这里插入图片描述

完成品

以下是细微完善过的最终源代码:

struct IndicatorProgressViewStyle: ProgressViewStyle {private let labelWidth = 40.0private let viewHeight = 20.0var color: AnyShapeStyle?func makeBody(configuration: Configuration) -> some View {let progress = configuration.fractionCompleted ?? 0.0VStack {Capsule(style: .continuous).opacity(0.0).overlay {GeometryReader { geo inVStack {VStack {if let curLabel = configuration.currentValueLabel {curLabel}else{Text("\(String(format: "%.0f%%", progress * 100))")}Image(systemName: "arrowtriangle.down.fill")}.minimumScaleFactor(0.8).font(.headline).frame(width: labelWidth).offset(x: progress * geo.size.width - labelWidth / 2, y: -40)}ZStack(alignment: .topLeading) {Capsule(style: .continuous).foregroundStyle(Color.gray.opacity(0.3))Capsule(style: .continuous).foregroundStyle(color != nil ? color! : AnyShapeStyle(.teal.gradient)).frame(width: progress * geo.size.width).shadow(radius: 3.0)}.clipShape(Capsule(style: .continuous))}}.frame(height: viewHeight)configuration.label}}
}

总结

在本篇博文中,我们利用敏捷开发中“曳光弹”原则步步为营打造了一款漂亮的进度条样式;我们最终完美的实现了目标,更重要的是:我们学到了软件工程中重要的一课!

感谢观赏,再会!!!😎

这篇关于SwiftUI 内功:“曳光弹“实现自定义样式进度条(ProgressView)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/203465

相关文章

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入