gpt4 book ai didi

ios - 添加核心数据项后以编程方式生成 View

转载 作者:行者123 更新时间:2023-12-04 15:10:53 25 4
gpt4 key购买 nike

我正在开发一个 SwitUI 应用程序,它显示了我想要创建/编辑/删除的项目列表。我一直在使用核心数据,所以我在检索对象的 View 中有一个@FetchRequest。然后是一个“+”按钮,它使用核心数据上下文创建一个新对象,带有一个占位符标题,并将其添加到列表中。然后,用户可以点击以编辑列表中的对象,以使用编辑器 View 向其添加信息。

我的问题是,有没有一种方法可以在创建新对象并传入同一对象时以编程方式打开编辑器 View ?

我可能遗漏了一些简单的东西,但我正在努力实现它。我无法在父 View 层次结构中创建编辑器 View ,也无法通过切换 @State 变量来显示它,因为在实例化 View 时我没有新创建的对象。

这里有一些伪代码可以帮助更清楚地说明:

    @FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Object.title, ascending: true)],
animation: .default) private var objects: FetchedResults<Object>

@State var objectEditorIsActive: Bool = false

var body: some View {

List {

Button(action: {
addObject()
}, label: { Image(systemName: "plus") })

// List of existing objects, with a button to open ObjectEditor
// and pass in the corresponding object for editing.

NavigationLink(
destination: ObjectEditor(object: existingObject),
isActive: $objectEditorIsActive,
label: { ObjectView() })

}


}

func addObject() {
withAnimation {
let newObject = Object(context: viewContext)
newObject.title = "New Object"
try? viewContext.save()
// if this is successful, open ObjectEditor with newObject passed in.
// Via NavigationLink ideally, but in a sheet or any other method is fine.
}
}


所以基本上我想打开 ObjectEditor 并一键传入 newObject,而不是要求用户每次都必须专门选择新创建的对象。

如有任何帮助,我们将不胜感激!

最佳答案

这里是可能的方法 - 这个想法是使用动态绑定(bind)到新创建对象的状态属性并以编程方式激活隐藏的导航链接。

使用 Xcode 12.1/iOS 14.1 测试

@State private var newObject: Object?
private var isNewObject: Binding<Bool> {
Binding(get: { self.newObject != nil }, // activate when state is set
set: { _ in self.newObject = nil }) // reset back
}

...

List {

Button(action: {
addObject()
}, label: { Image(systemName: "plus") })

// List of existing objects, with a button to open ObjectEditor
// and pass in the corresponding object for editing.

}
.background(
NavigationLink(
destination: ObjectEditor(object: newObject),
isActive: isNewObject, // << activated programmatically !!
label: { EmptyView() })
)

...

func addObject() {
withAnimation {
let newObject = Object(context: viewContext)
newObject.title = "New Object"

if let _ = try? viewContext.save() {
self.newObject = newObject // << here !!
}
}
}

关于ios - 添加核心数据项后以编程方式生成 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65223557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com