【问题标题】:SwiftUI - update view after adding CoreData recordSwiftUI - 添加CoreData记录后更新视图
【发布时间】:2020-08-02 03:56:14
【问题描述】:

当用户想要创建新记录时,我想 a) 转到新视图,b) 在.onAppear 期间创建记录,然后 c) 使用新创建的记录更新视图。

第一部分很简单。我有一个NavigationLink,它与用户名一起作为属性进入新视图。我可以在.onAppear 期间创建新记录。但这是事情变得棘手的最后一部分。

我尝试使用同时手势创建记录和切换视图,我尝试使用切换视图功能加载新视图,以及大约十几个灵感较少的想法。问题总是归结为:如何在新记录创建后更新 FetchRequest? 注意:我需要对新创建记录的引用,以便用户可以添加内容到记录。

这是目前为止的代码...

struct RecordView: View {
    
    @Environment(\.managedObjectContext) var moc
    let appDelegte = UIApplication.shared.delegate as! AppDelegate
    
    var fetchedRecords: FetchRequest<Record>
    var currentUser: User
    
    init(recordNumber: String) {
        fetchedRecords = FetchRequest<Record>(entity: Record.entity(), sortDescriptors: [], predicate: NSPredicate(format: "user.recordNumber = %@", recordNumberNumber))
    }
    
    var body: some View {
        Text(fetchedRecords.wrappedValue.first.recordNumber)
        
    }
    .onAppear {
        self.CreateNewRecord()
    }
    
    func CreateNewRecord() {
        let newRecord = Record(context: self.moc)
        newRecord.id = UUID()
        let recordNumber = "AABBCCDDEE"
        
        user.addToRecords(newRecord)
        appDelegate.saveContext()

    //This is when the fetched request should fetch the new record and the Text view should be updated.
    }
}

【问题讨论】:

    标签: swiftui nsfetchrequest


    【解决方案1】:

    我对您说要在用户创建记录时创建记录 onAppear 有点困惑?无论如何,我可能会为文本创建一个变量并将其设置为 onAppear 函数内的新记录。虽然整个 onAppear 创建记录仍然让我感到困惑,并且可能会使变量的实现更加困难。

    【讨论】:

    • 我应该说的是,“当用户想要创建新记录时......”换句话说,它还没有发生。如果我不需要对新创建的记录的引用,变量会很好用。欢迎来到堆栈溢出!
    【解决方案2】:

    正如@kontiki 所解释的那样,最终起作用的是将 NavigationLink 与 Button 结合起来。这让我可以在进入新视图之前创建一个新记录。我不确定这是最好的解决方案,但它确实有效!下面的代码展示了解决方案背后的理论。

    @State private var presentMe = false
    @State var currentNumber = 10
        
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink(destination: SecondView(number: currentNumber), isActive: $presentMe) { EmptyView() }
                    
                    Button(action: {
                    //This is where I created a new record and saved to Core Data
                        self.currentNumber = 5 
                        //I was then able to pass the new record to the second view through the navigation link
                        self.presentMe = true
                    }) {
                        Text("Go to SecondView")
                    }
                }
            }
        }
    }
    
    struct SecondView: View {
        var number: Int
        
        var body: some View {
            Text("The number is now = \(number)") //The number is now = 5
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多