ProgressManager
是一个类,旨在使处理 Progress
及其子任务变得更直接和容易。 为什么要使用它? 它允许对多步操作的细节进行细粒度但易于访问的控制,同时自动将其状态反映在诸如 ProgressView
、UIProgressView
和 NSProgressIndicator
等视图中。
ChildProgressTask
的东西)。 它必须具有两个属性:childUnits
和 parentUnits
。 有关更多信息,请参阅文档。private enum ProgressSteps: ChildProgressTask {
case importantStep, smallStep, aMultiUnitStep
var childUnits: Int64 {
switch self {
// 1 unit of this task must be completed for it to be considered "complete" by the parent
case .importantStep: 1
// 1 unit of this task must be completed for it to be considered "complete" by the parent
case .smallStep: 1
// 6 units of this task must be completed for it to be considered "complete" by the parent
case .aMultiUnitStep: 6
}
}
var parentUnits: Int64 {
switch self {
// Once all units of this child task have been completed (1 unit),
// it counts as 5 units in the context of the parent progress
case .importantStep: 5
// Once all units of this child task have been completed (1 unit),
// it counts as 1 unit in the context of the parent progress
case .smallStep: 1
// Once all units of this child task have been completed (6 units),
// it counts as 1 unit in the context of the parent progress
case .aMultiUnitStep: 1
}
}
}
ProgressManager
的实例。 初始化 ProgressManager
时,您只需要向其提供一个它关心的任务的 Set
。 如果您的类型符合 CaseIterable
,您甚至可以排除初始值设定项的 childTasks
参数。let progress = ProgressManager(
// can be ommitted if type can be inferred
ProgressSteps.self,
// a Set of unique child tasks
childTasks: [.importantStemp, .smallStep, .aMultiUnitStep]
)
setCompletedUnitCount(_:forChildTask:)
、addToCompletedUnitCount(_:forChildTask:)
和 updateCompletedUnitCount(forChildTask:updateClosure:)
)。// Perform `.importantStep`.
progress.setCompletedUnitCount(1, forChildTask: .importantStep)
// Perform `.smallStemp`.
progress.setCompletedUnitCount(1, forChildTask: .smallStemp)
// Perform `.aMultiUnitStep`.
for i in 0..<6 {
progress.addToCompletedUnitCount(i, forChildTask: .aMultiUnitStep)
}
就是这样! 如果您需要更细粒度的控制,您可以通过 childTasks
属性或者直接通过下标(progress[.aMultiUnitStep]
)访问子任务。