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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import