SwiftUI 如何将核心数据对象详细信息传递给详细信息视图

问题描述 投票:0回答:1

我有显示联系人行(核心数据实体)的视图。选择一行后,我想在 DetailView 中显示所选联系人的详细信息。如何将 Contact 实体中的属性 contact.uniqueID 传递给 DetailView?然后我可以从核心数据中提取联系人实体的数据并显示其详细信息。有没有比这更好的方法,请告诉我。

struct ContentView: View {
NavigationView {
    List {
        ForEach(contacts) { contact in
            NavigationLink {
                DetailView()
            } label: {
                HStack {
                    Text(contact.firstName! + " " + contact.lastName!)
                }
            }
        }
        .onDelete(perform: deleteItems)
    }
    .navigationTitle("Contacts")
    ToolbarItem {
        NavigationLink {
            AddContactView()
        } label: {
            Label("Add Contact", systemImage: "plus")
                .foregroundColor(.black)
        }
    }
    
}

}

编辑:

NavigationView {
     List {
         ForEach(contacts) { contact in
         
             NavigationLink {
                DisplayContactView(contact: contact)
             }
        }
    }
 }

然后在 DisplayView 中

struct DisplayView: View {
init(contact: Contact) {
    _contact = StateObject(wrappedValue:contact)
}
var body: some View
{ 
    NavigationView
    {
        VStack
        {
            TextField("Full Name", text: $contact.firstName!)
        }
    }
  }


}

我收到错误消息:在 TextField 上

无法转换“字符串”类型的值?预期的参数类型“绑定”错误:在 TextField

swiftui core-data
1个回答
0
投票

这是一个简单的方法——因为核心数据使用一个对象,它已经有一个 ID,它是它的指针,所以你不需要查找它,例如

//
//  ContentView.swift
//
//  Created by Malcolm Hall on 28/04/2023.
//
// Demonstrates modifying the default Xcode template from NavigationView to NavigationStack

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationStack {
            List {
                ForEach(items) { item in
                    NavigationLink(value: item) {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .navigationDestination(for: Item.self) { item in
                Text("Item at \(item.timestamp!, formatter: itemFormatter)")
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            //Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.