摘要: 我正在创建一个具有三个视图和相同的"设置"按钮的应用程序,该按钮导航到每个视图右上角的列表视图。当我选择"设置"图标时,它会在弹出的列表视图中显示滑块、步进器和切换开关。
我能够使用以下代码初始化值,并且在运行应用程序时,我能够在"设置"视图中更改数据,但是我遇到的问题是退出设置视图时数据未保留。
Xcode 11 Beta 4 从 didChange 更新为 willChange 作为 BindableObject 更新的一部分,这可能是我问题的一部分,因为它的实现方式可能不同。
问题: 1) 退出设置视图时,主视图中的数据不会更新。
2)当我再次选择"设置"视图时,它显示初始化的值,而不是我之前更改的值。
预期成果: 我希望我的个人资料数据使用"设置"应用中定义的新值进行更新
我的数据存储(配置文件.swift)
import SwiftUI
import Combine
class Profile: BindableObject {
var willChange = PassthroughSubject<Void, Never>()
var test1 = 16 { willSet { update() }}
var test2: Double = 10 { willSet { update() }}
var test3 = true { willSet { update() }}
func update() {
willChange.send()
}
}
我的设置视图(配置文件摘要.swift)
import SwiftUI
struct ProfileSummary: View {
//var profile: Profile
@ObjectBinding var profile = Profile()
var body: some View {
List {
Stepper(value: $profile.test1, in: 12...22) {
Text("Test1 Size: (profile.test1)")
}
Text("Quiz Settings")
.bold()
HStack {
Text(" Test2: (Int(profile.test2))")
Slider(value: $profile.test2, from: 1.0, through: 107.0, by: 1.0)
}
Toggle(isOn: $profile.test3) {
Text(" Change to Test3")
}
}
}
}
#if DEBUG
struct ProfileSummary_Previews: PreviewProvider {
static var previews: some View {
ProfileSummary()
}
}
#endif
我的主要观点(Test_List.swift):
import SwiftUI
import UIKit
struct Test_List : View {
@ObjectBinding var profile: Profile = Profile()
@State var showingProfile = false
var profileButton: some View {
Button(action: { self.showingProfile.toggle() }) {
Text("Settings")
.padding()
}
}
var body: some View {
NavigationView {
VStack(alignment: .center){
Text("Test1: (profile.test1)")
Text("Test2: (profile.test2)")
Spacer()
}
.navigationBarTitle(Text("View3"))
.navigationBarItems(trailing: profileButton)
.sheet(isPresented: $showingProfile) {
ProfileSummary()
}
}
}
}
#if DEBUG
struct Test_List_Previews : PreviewProvider {
static var previews: some View {
Test_List()
}
}
#endif
您正在Test_List
中创建Profile
:
struct Test_List : View { @ObjectBinding var profile: Profile = Profile()
然后你在ProfileSummary
中创建了一个全新的Profile
:
struct ProfileSummary: View { //var profile: Profile @ObjectBinding var profile = Profile()
因此,您的ProfileSummary
视图会编辑它创建的Profile
,而不是Test_List
创建的Profile
。
您需要将您在Test_List
中创建的Profile
传递给ProfileSummary
,以便ProfileSummary
编辑与Test_List
使用的相同Profile
:
struct Test_List : View {
...
.sheet(isPresented: $showingProfile) {
ProfileSummary(profile: self.profile)
// ^^^^^^^^^^^^^^^^^^^^^ add this
}
您可能还应该更改ProfileSummary
,以免自己创建新Profile
,因为这会浪费资源:
struct ProfileSummary: View {
@ObjectBinding var profile: Profile
// ^^^^^^^^^ declare the type; don't set a default value