如何使用对象填充@State var?

时间:2020-02-11 17:21:37

标签: class swiftui ios13

我正在尝试将Class中的信息与State元素“绑定”:

let people = People(name: "Jonnathan", firstSurname: "Bree")

@State private var name = people.name
@State private var firstSurname = people.firstSurname

但是当我尝试执行此操作时,出现此错误:

不能在属性初始化程序中使用实例成员“ people”;属性初始化程序在“自我”可用之前运行

使用未解决的标识符“自身”

如果尝试在对象之前添加.self

非常感谢您!

1 个答案:

答案 0 :(得分:1)

这是可行的方法

let people = People(name: "Jonnathan", firstSurname: "Bree")

@State private var name: String
@State private var firstSurname: String

init() {
    _name = State<String>(initialValue: people.name)
    _firstSurname = State<String>(initialValue: people.firstSurname)
}