SwiftUI 小问题之 02 为什么我的数组总是零,我试图向数组添加一个项目以共享文档QLView
实战问题
我试图共享一个PDF文档,该文档正在使用Quick Look视图显示。我可以正确地看到PDF视图中加载的PDF,但我无法将PDF路径添加到arrayItemToShare中。
我尝试过很多东西,但找不到这个代码没有添加任何东西的原因!
arrayItemToShare?.append(report.pathFile!)
低于我报告视图的代码。
···
struct listReport: View {
@ObservedObject var dm : DataManager
var report : UserReport
@State var openQL = false
@State var share = false
@State var arrayItemToShare : [String]?
var body: some View {
Button(action: {
openQL.toggle()
}, label: {
VStack(alignment: .center, spacing: 60){
if report.urlFile != nil {
PDFThumbnailRepresented(urlDoc: report.urlFile!).padding()
}
Spacer()
Text(report.id_report_show).foregroundColor(.primary).bold()
}
})
.sheet(isPresented: $openQL, content: { // open sheet to preview PDF
fakebar
if report.pathFile != nil {
QLView(filePath: report.pathFile!, isPresented: $openQL) // open Quick Look and preview the file pdf at path
.onAppear {
arrayItemToShare?.append(report.pathFile!) // why this not adding the value to the array
print("count \(arrayItemToShare!.count)") // here the crash because array is NIL
}
} else {
Text("OPS!!.. unable to load pdf")
}
})
.sheet(isPresented: $share) {
ShareSheet(item: arrayItemToShare!)
}
}
var fakebar: some View {
ZStack {
HStack {
Button(action: {
if report.urlFile != nil {
openQL.toggle() // close preview pdf
share.toggle() // open share sheet
}
}) {
Image(systemName: "square.and.arrow.up")
.foregroundColor(.white)
.padding(.horizontal)
}
Spacer()
Image(systemName: "chevron.compact.down")
.font(.system(size: 60))
.aspectRatio(contentMode: .fit)
.foregroundColor(.white)
Spacer()
Button(action: {
openQL.toggle()
}) {
Text("Close")
.fontWeight(.bold)
.foregroundColor(.white)
.padding(.horizontal)
}
}
}
.frame(height: 44)
.background(Color("AMUColor").padding(.top, -44))
}
}
我在带有foreach循环的scrollView中使用了这个(listReport:View),在那里一切都很好。
解决方案
这里有一个修复方法:
QLView(filePath: report.pathFile!, isPresented: $openQL) // open Quick Look and preview the file pdf at path
.onAppear {
if nil == arrayItemToShare {
arrayItemToShare = [String]() // << create if needed !!
}
arrayItemToShare?.append(report.pathFile!)
print("count \(arrayItemToShare!.count)")
}
加入我们一起学习SwiftUI
QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com