本文介绍了SwiftUI 未知属性“可观察对象"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在下面的 @ObservableObject var dataSource = DataSource() 调用旁边收到错误 Unknown attribute ObservableObject.ObservableObject 几天前在另一个项目中工作得很好,但现在不行了.

So I'm getting the error Unknown attribute ObservableObject next to the @ObservableObject var dataSource = DataSource() call below. the ObservableObject worked perfectly a couple days ago in another project but not anymore.

import SwiftUI
import Combine


class DataSource: ObservableObject {

    var willChange = PassthroughSubject<Void,Never>()


    var expenses = [Expense]() {
        willSet { willChange.send() }
    }
    var savingsItems = [SavingsItem](){
        willSet { willChange.send() }
    }

    //@State var monthlyIncomeText: String
    //var monthlyIncome: Int = 1364


    init(){
        addNewExpense(withName: "Spotify", price: 14)

    }

    func addNewExpense(withName name: String, price: Int){
        let newExpense = Expense(name: name, price: price)
        expenses.append(newExpense)
    }

     func addNewSavingsItem(withName name: String, price: Int, percentage: Double){
        let newSavingsItem = SavingsItem(name: name, price: price, timeTilCompletion: 0, percentage: percentage)
        savingsItems.append(newSavingsItem)
    }
}

struct ContentView: View {

    @ObservableObject var dataSource = DataSource()

    var body: some View {
        VStack{
            Text("Expenses")
            List(dataSource.expenses) { expense in
                ExpenseRow(expense: expense)
            }
        } 
    } 
}

有人可以帮忙吗?

推荐答案

ObservableObjectObservedObject 必须遵守的协议.有关 ObservableObject此处 获取有关 ObservedObject 的文档,这是您正在寻找的属性包装器.将您的 ContentView 代码更改为:

ObservableObject is a protocol that ObservedObjects must conform to. See here for documentation on ObservableObject, and here for documentation on ObservedObject, which is the property wrapper that you are looking for. Change your ContentView code to this:

struct ContentView: View {

    @ObservedObject var dataSource = DataSource()

    var body: some View {
        VStack {
            Text("Expenses")
            List(dataSource.expenses) { expense in
                ExpenseRow(expense: expense)
            }
        } 
    } 
}

这篇关于SwiftUI 未知属性“可观察对象"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:10