默认情况下,控制Progress子级仅使将子级添加到Progress实例变得容易,而默认情况下则无法删除。 当您要使用一个随时间推移具有不同子级的Progress实例时,这可能会很有用。 使用自定义类MutableProgress使这成为可能。
Progress
自Swift 3.0起, NSProgress实例已重命名为Progress ,它是在Swift中用于进度报告的主要类。 通过我们自己管理孩子,我们可以控制孩子并增加删除孩子的可能性。
NSProgress
// Remove the Video upload progress, as the video file has been deleted by the user during upload. totalUploadProgress.removeChild(videoUploadProgress)
通过这样做,我们需要确保正确广播更新。 因此,我们需要覆盖属性fractionCompleted , totalUnitCount和completedUnitCount 。 Progress是在内部使用键值观察。 使用willChange和didChange可增加与willChange等UI元素的UIProgressView 。
fractionCompleted
totalUnitCount
completedUnitCount
willChange
didChange
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类。
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
print(totalUploadProgress.fractionCompleted) // 1.0 print(totalUploadProgress.isCompleted) // true
这个故事最初发布在: https : //www.avanderlee.com/swift/controlling-progress-children/