通过添加删除控制进度儿童

默认情况下,控制Progress子级仅使将子级添加到Progress实例变得容易,而默认情况下则无法删除。 当您要使用一个随时间推移具有不同子级的Progress实例时,这可能会很有用。 使用自定义类MutableProgress使这成为可能。

通过将进度子类化来控制进度儿童

自Swift 3.0起, NSProgress实例已重命名为Progress ,它是在Swift中用于进度报告的主要类。 通过我们自己管理孩子,我们可以控制孩子并增加删除孩子的可能性。

 // Remove the Video upload progress, as the video file has been deleted by the user during upload. 
totalUploadProgress.removeChild(videoUploadProgress)

通过这样做,我们需要确保正确广播更新。 因此,我们需要覆盖属性fractionCompletedtotalUnitCountcompletedUnitCountProgress是在内部使用键值观察。 使用willChangedidChange可增加与willChange等UI元素的UIProgressView

 /// Removes the given child from the progress reporting. 
///
/// - Parameter child: The child to remove.
func removeChild(_ child: Progress) {
willChangeValue(for: \.fractionCompleted)
willChangeValue(for: \.completedUnitCount)
willChangeValue(for: \.totalUnitCount)
children.removeValue(forKey: child)?.invalidate()
didChangeValue(for: \.totalUnitCount)
didChangeValue(for: \.completedUnitCount)
didChangeValue(for: \.fractionCompleted)
}

检查进度是否完成

通过使用简单的扩展,可以很容易地验证Progress实例是否完成。

 private extension Progress { 
var isCompleted: Bool {
guard totalUnitCount > 0 else { return true }
return completedUnitCount >= totalUnitCount
}
}

在操场上使用代码

您可以使用游乐场轻松地进行尝试,并在其中包括MutableProgress 。 您可以在此处找到自定义MutableProgress类。

 let totalUploadProgress = MutableProgress() 
let imageUploadProgress = Progress(totalUnitCount: 1)
let videoUploadProgress = Progress(totalUnitCount: 1)
 totalUploadProgress.addChild(imageUploadProgress) 
totalUploadProgress.addChild(videoUploadProgress)
 // Mark Image uploading as completed 
imageUploadProgress.completedUnitCount = 1
 print(totalUploadProgress.fractionCompleted) // 0.5 
print(totalUploadProgress.isCompleted) // false
 // Remove the Video upload progress, as the video file has been deleted by the user during upload. 
totalUploadProgress.removeChild(videoUploadProgress)
 print(totalUploadProgress.fractionCompleted) // 1.0 
print(totalUploadProgress.isCompleted) // true

这个故事最初发布在: https : //www.avanderlee.com/swift/controlling-progress-children/