使用协议定义swiftui视图的属性

时间:2020-02-03 04:56:01

标签: swiftui

我有多个要与预算选择器视图一起使用的类。他们都定义了此预算协议。

import SwiftUI

struct BudgetPickerView: View {
    @EnvironmentObject var userData: UserData
    @State var budgetable: Budgetable
    ...
}
import Foundation

protocol Budgetable
{
    var budgetId: String { get set }
}

例如此分配类

import Foundation
import Combine

class Allocation: ObservableObject, Identifiable, Budgetable {
    let objectWillChange = ObservableObjectPublisher()

    let id: String?
    var amount: String { willSet { self.objectWillChange.send() } }
    var budgetId: String { willSet { self.objectWillChange.send() } }

    init(id: String? = nil, amount: String, budgetId: String) {
        self.id = id
        self.amount = amount.removePrefix("-")
        self.budgetId = budgetId
    }
}

但是,当我尝试将分配传递到预算选择器视图时,出现错误

NavigationLink(destination: BudgetPickerView(budgetable: allocation))...

无法将类型为“ NavigationLink>,BudgetPickerView>”的返回表达式转换为类型为“ some View”的

表达类型'BudgetPickerView'是模棱两可的,没有更多上下文

2 个答案:

答案 0 :(得分:0)

更改为以下代码

struct BudgetPickerView: View {
   @EnvironmentObject var userData: UserData
   var budgetable: Budgetable
   var body: some View {
   ...
   }
}

NavigationLink(destination: BudgetPickerView(budgetable: allocation).EnvironmentObject(UserData()))

答案 1 :(得分:0)

通过SwiftUI概念,您不允许在View之外使用@State,但是以下方法可以很好地工作(保持其他部分不变)

struct BudgetPickerView: View {
    @State private var budgetable: Budgetable

    init(budgetable: Budgetable) {
        _budgetable = State<Budgetable>(initialValue: budgetable)
    }

    var body: some View {
        Text("Hello, World!")
    }
}
struct TestBudgetPickerView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: 
               BudgetPickerView(budgetable: Allocation(amount: "10", budgetId: "1"))) 
               { Text("Item") }
        }
    }
}

顺便说一句,顺便说一句,顺便说一句,@ State旨在保存仅临时视图状态数据,而不是模型。对于模型,更可取的是使用ObservableObject。就您而言,Budgetable看起来像是一个模型。