您的位置:首页 > 移动开发 > Swift

SwiftUI 简明教程之指示器

2021-05-11 20:28 886 查看

本文为 Eul 样章,如果您喜欢,请移步 AppStore/Eul 查看更多内容。

Eul 是一款 SwiftUI & Combine 教程 App(iOS、macOS),以文章(文字、图片、代码)配合真机示例(Xcode 12+、iOS 14+,macOS 11+)的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI & Combine 相关的知识,使读者能快速掌握并在 iOS 开发中实践。

ProgressView

ProgressView 有两种呈现形式,一种是菊花样式,另一种是进度条样式,二者分别对应 ProgressViewStyle 中的 CircularProgressViewStyleLinearProgressViewStyle

如果我们没有通过绑定的浮点类型的值动态更新 ProgressViewvalue 值,那么它的默认样式就是 CircularProgressViewStyle,即菊花样式。比如:

ProgressView()

或者:

ProgressView("加载中...")

我们还可以通过

.foregroundColor(.blue)
改变文字的颜色,如果我们要修改菊花的颜色,那么可以这样指定:
.progressViewStyle(CircularProgressViewStyle(tint: .orange))

而要修改进度条的颜色,则可以通过

.accentColor(.orange)
实现。

进度条样式的实现也比较简单,当然我们也可以自定义 ProgressViewStyle

如下是示例所示的全部代码,供参考:

struct IndicatorsView: View {
@State private var progress = 0.0 {
didSet {
if progress == 100 {
title = "下载完成!"
systemImgName = "checkmark.seal.fill"
} else {
title = "下载ing..."
systemImgName = "square.and.arrow.down"
}
}
}
@State private var title = "下载ing..."
@State private var systemImgName = "square.and.arrow.down"
/// 定时器
private let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()

var body: some View {
List {
// SectionHeaderView 是笔者自定义的视图控件
Section(header: SectionHeaderView(chapter: "ProgressView", section: nil)) {
ProgressView().centerHorizontal() // .centerHorizontal() 是笔者自定义的修饰器

ProgressView("加载中...").progressViewStyle(CircularProgressViewStyle(tint: .orange))
.centerHorizontal()
.footnote(".progressViewStyle(CircularProgressViewStyle(tint: .orange))")

ProgressView(title, value: progress, total: 100)
.foregroundColor(.blue)
.accentColor(.orange)
.footnote(".foregroundColor(.blue)\n.accentColor(.orange)")

ProgressView(value: progress, total: 100) {
HStack {
Image(systemName: systemImgName)
Text(title)
}
.foregroundColor(.blue)
} currentValueLabel: {
Text("\(Int(progress))%").foregroundColor(.orange)
}
.footnote("自定义视图")
}
.onReceive(timer) { _ in // 接收定时器更新事件
if progress < 100 {
progress = min(100, progress + Double(arc4random_uniform(5)+1))
}
}
}
.listStyle(InsetGroupedListStyle())
}
}


本文为 Eul 样章,如果您喜欢,请移步 AppStore/Eul 查看更多内容。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: