【发布时间】:2020-10-15 16:02:08
【问题描述】:
我有一个进度条,在使用 fileImporter 修饰符处理文件时更新了它的值。我不确定为什么在处理文件时进度条没有更新(是因为它是关闭的一部分吗?)。下面是我如何实现进度条。非常感谢任何帮助!
ContentView 基本上有一个按钮,它使用按钮和闭包中的 .fileImporter 修饰符触发对所选文件的处理。
struct ContentView: View {
@ObservedObject var progress = ProgressItem()
@State var importData: Bool = false
var body: some View {
VStack {
Button(action: {importData = true}, label: {Text("Import Data")})
.fileImporter(isPresented: $importData, allowedContentTypes: [UTType.plainText], allowsMultipleSelection: false) { result in
do {
guard let selectedFile: URL = try result.get().first else { return }
let secured = selectedFile.startAccessingSecurityScopedResource()
DataManager().importData(fileURL: selectedFile)
if secured {selectedFile.stopAccessingSecurityScopedResource()}
} catch {
print(error.localizedDescription)
}
}
ProgressBar(value: $progress.progress).frame(height: 20)
}
}
}
ProgressBar 是一个简单的视图,它获取进度值并更新它
struct ProgressBar: View {
@Binding var value: Double
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle().frame(width: geometry.size.width , height: geometry.size.height)
.opacity(0.3)
.foregroundColor(Color(UIColor.systemTeal))
Rectangle().frame(width: min(CGFloat(self.value)*geometry.size.width, geometry.size.width), height: geometry.size.height)
.foregroundColor(Color(UIColor.systemBlue))
.animation(.linear)
Text("\(value)")
}.cornerRadius(45.0)
}
}
}
我有一个 ProgressItem 类,它是一个包含进度值的 ObservableObject:
class ProgressItem: ObservableObject {
@Published var progress: Double = 0
@Published var message: String = ""
}
文件作为 DataManager 类的一部分进行处理。为了这个问题,我已经剥离了处理细节,只是有一个打印语句来打印出每一行。下面是更新ProgressValue的DataManager类
class DataManager {
@Published var progressBar: ProgressItem? = nil
init() {
progressBar = ProgressItem()
}
func importData(fileURL: URL, delimeter: String = ",") {
let lines = try! String(contentsOf: fileURL, encoding: .utf8).components(separatedBy: .newlines).filter({!$0.isEmpty})
let numlines = lines.count
for index in 0..<numlines {
let line = String(lines[index])
print("\(line)")
progressBar?.progress = Double(index)/Double(numlines) * 100
}
}
}
【问题讨论】:
标签: ios swift swiftui progress-bar