【问题标题】:Cannot use instance member 'pdfName' within property initializer; property initializers run before 'self' is available不能在属性初始化器中使用实例成员“pdfName”;属性初始化程序在“自我”可用之前运行
【发布时间】:2020-12-12 00:01:28
【问题描述】:

我正在尝试打开与列表中所选行的名称相匹配的 pdf,但我收到错误 Cannot use instance member 'pdfName' within property initializer; property initializers run before 'self' is available

我尝试初始化在视图之间传递的变量名,但没有运气。我知道这很简单,但我在传递数据时总是感到困惑。

这是第一个视图中的UIButton

@State var showingDetail = false

ForEach(0..<product.applicationNotes.count, id: \.self) { item in
                Button(action: {
                    self.showingDetail.toggle()
                }) {
                    Text(product.applicationNotes[item])
                }.sheet(isPresented: $showingDetail) {
                    PDFKitView(pdfName: product.applicationNotes[item])
                }

这是我尝试将数据传递到的第二个视图。我在第二行收到错误documentURL:

    var pdfName: String
    var documentURL = Bundle.main.url(forResource: pdfName, withExtension: "pdf")!
    var body: some View{ PDFViewer(url: documentURL) .ignoresSafeArea(edges:.bottom) }  }

struct PDFViewer: UIViewRepresentable {
    
    var url: URL
    func makeUIView(context:
        UIViewRepresentableContext<PDFViewer>) -> PDFViewer.UIViewType {
        let pdfView = PDFView()
        pdfView.document = PDFDocument(url: self.url)
        return pdfView
    }
    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFViewer>) {
    }
}

这是我试图初始化它但不知道我哪里出错了:

 init() {
    self.pdfName = self.documentURL()
 }

【问题讨论】:

  • 我认为这个问题有一个简单的答案,但我认为一个最小(或至少“本地完成”)的例子会有所帮助。您发布了一些代码片段,但目前还不清楚(至少对我而言)它们在哪里以及它们之间的关系如何。也许您可以编辑帖子以使示例更易于理解。

标签: ios xcode swiftui


【解决方案1】:

几个问题:

  1. 您正在使用其上方的 pdfName 属性初始化 documentURL,这在 SwiftUI 结构中是禁止的。这就是你得到的错误。

    var documentURL = Bundle.main.url(forResource: pdfName, withExtension: "pdf")!

  2. 在 init 方法中,您将一个 URL 属性分配回 pdfName String 属性。

    self.pdfName = self.documentURL()

SwiftUI 已经为 pdfName 属性设置了一个 init,去掉 init 和 documentURL 属性,试试这个:

struct PDFKitView {
    var pdfName: String
    
    var body: some View {
        PDFViewer(url: Bundle.main.url(forResource: self.pdfName, withExtension: "pdf")!)
            .ignoresSafeArea(edges:.bottom)
    }
}

它并不理想,但会让您摆脱尝试使用另一个 Struct 属性的值初始化 Struct 属性的问题。将 .onAppear() 视为设置辅助属性的更好方法。无论如何,我不建议在 init 方法中进行资源获取,onAppear 会是一个更好的地方。

【讨论】:

  • 这太好了,感谢您深入解释我哪里出错了!
猜你喜欢
  • 2021-03-19
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2021-04-03
相关资源
最近更新 更多