如何删除核心数据SwiftUI? [英] How to delete Core Data SwiftUI?

查看:72
本文介绍了如何删除核心数据SwiftUI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉这个愚蠢的问题,但我已经搜索了大约两天的答案,并尝试了许多方法来处理它。

我在核心数据上运行的WatchOS应用程序。有3个视图:

  1. 第一视图-包含用于添加新目标和已添加目标列表的按钮的视图。
  2. 添加目标视图-按"添加新目标"后显示。
  3. RingView-带有目标环的视图(类似于活动环机制)和显示的所有数据。

因此,我尝试让用户有机会直接在第一个视图中删除创建的目标。在不同的迭代之后,我了解到,删除按钮在RingView中起作用,但在第一个视图上不起作用。您能谈谈您对这个问题的看法吗(如果可以,请给出一个.onDelete变体)?

以下是我的Firstview代码:

struct FirstView: View {
@Environment(.managedObjectContext) var context
@Environment(.presentationMode) var presentationMode
@FetchRequest (
    entity:NewGoal.entity(),
    sortDescriptors:[NSSortDescriptor(keyPath: NewGoal.dateAdded, ascending: false)],
    animation: .easeInOut )
var results:FetchedResults<NewGoal>
var body: some View {

    ScrollView{
        VStack{
        VStack(alignment: .leading){
    NavigationLink(
            destination: AddGoalView(),
            label: {
                Image(systemName: "plus")
                Text("Set Money Goal")
            })
        .frame(maxWidth: .infinity)
        .clipShape(RoundedRectangle(cornerRadius: 9))
        
         VStack(alignment: .leading){
            ForEach(results){ item in
                NavigationLink(
                    destination: RingView(goalItem: item, GTitle: item.goalTitle ?? "", Sum: item.neededSum, summarize: item.yourSum),
                    label: {

                        HStack{
                                Button(action: deleteGoal){
                                    Text("Delete") } //// < --- Here it is

                            Text(item.goalTitle ?? "")
                            Text("$(item.yourSum, specifier: "%.f")")
                            Text("/ $(item.neededSum, specifier: "%.f")")
                        }
                    })  .contentShape(Rectangle())
                        .clipShape(RoundedRectangle(cornerRadius: 9))
                   }
               }
            }
     }
   }
 }
    /////MY DELETE FUNC
  private func deleteGoal(){
        let goal = NewGoal (context: context)
        context.delete(goal)
        do{
            try context.save()
            presentationMode.wrappedValue.dismiss()
        } catch let err{
            print(err.localizedDescription)
            }
    }
    }

以下是我的RingView代码(一切正常):

struct RingView: View {
@State private var isFocused = false
@State private var isFocusedSum = false
@State private var name: String = ""
@State var dayindex = 0
@State private var yournewSum:Double = 0.0
var goalItem: NewGoal?
var GTitle:String
var Sum:Double
var summarize:Double
var allNewSum:Double = 0.0

@Environment(.managedObjectContext) var context
@Environment(.presentationMode) var presentationMode

@FetchRequest var results: FetchedResults<NewGoal>
init(goalItem: NewGoal? = nil, GTitle: String, Sum: Double, summarize: Double, allNewSum: Double){
self.GTitle = GTitle
self.Sum = Sum
self.goalItem = goalItem
self.summarize = summarize
self.allNewSum = allNewSum
    
let predicate = NSPredicate(format:"goalTitle == %@", GTitle)
self._results=FetchRequest(
    entity: NewGoal.entity(),
    sortDescriptors: [NSSortDescriptor(keyPath: NewGoal.dateAdded, ascending: false)],
    predicate: predicate,
    animation: .easeInOut
                           )
}

var body: some View {
    NavigationView{
    ForEach(results) { item in
    ZStack{
        RingShape()
            .stroke(style: StrokeStyle(lineWidth: 11, lineCap: .round))
                            .fill(AngularGradient(gradient: Gradient(colors: [.red, .pink, .red]), center: .center))
                            .opacity(0.35)
        RingShape(percent:(((yournewSum + summarize)/Sum*100)+0.1), startAngle: -90, drawnClockwise: false) ///FG Ring SUM
            .stroke(style: StrokeStyle(lineWidth: 11, lineCap: .round))
                            .fill(AngularGradient(gradient: Gradient(colors: [.red, .pink, .red]), center: .center))
        
        RingShape() ///BG Ring Date
            .stroke(style: StrokeStyle(lineWidth: 4, lineCap: .round))
                            .fill(Color.yellow)
                            .opacity(0.35)
                            .frame(width: 145, height: 145)
        RingShape(percent: (Double((item.pickedValueDateN - item.pickedValueDateN1)*100) / (Double(item.pickedValueDateN) + 1) + 0.1), startAngle: -90, drawnClockwise: false)
            .stroke(style: StrokeStyle(lineWidth: 4, lineCap: .round))
                            .fill(Color.yellow)
                            .frame(width: 145, height: 145)

        
        ///BUTTON
        HStack(alignment: .top){
            Spacer()
        Button(action: addSum) {
            Image(systemName: "checkmark.circle")
                        .font(.title3)
                        .opacity(1)
          } .buttonStyle(MyButtonStyle())
        .frame(width: 30.0, height: 30.0)
        .clipShape(Circle())
        .disabled((yournewSum + summarize) <= summarize)
       }
        .padding(.bottom, 135.0)
        .padding(.horizontal, 8.0)
        
        VStack(alignment: .trailing, spacing: 0.0){
            Spacer()
            Text("$((yournewSum + summarize), specifier: "%.f")")
                    .font(.title3)
                    .bold()
                    .padding(4)
                    .overlay(
                        RoundedRectangle(cornerRadius: 7)
                            .stroke(Color.white, lineWidth: 2)
                            .opacity(isFocusedSum ? 1.0:0.0)
                    )
                    .focusable(true) { newState in isFocusedSum = newState}
                    .animation(.easeInOut(duration: 0.3), value: isFocusedSum)
                    .digitalCrownRotation(
                        $yournewSum,
                        from: 0,
                        through: Double((Sum - summarize)),
                        by: 10,
                        sensitivity: .high
                    )
            
             
            Text("/ $(item.neededSum, specifier: "%.f")")
            .font(.caption)
            .foregroundColor(Color.gray)
            .padding(3.5)
            
            Button(action: deleteGoal){
                Text("HO")
            }
      
        Spacer()
        }
    .frame(width: 200, height: 230)
    .padding(.top, 15)

    }
    }
    .padding([.top, .leading, .trailing], 5.0)
    
 }
 }

private func addSum(){
    let goal = goalItem == nil ? NewGoal(context: context): goalItem
    goal?.yourSum = yournewSum + summarize
    goal?.allNewSum = yournewSum + allNewSum
    do{
        try context.save()
        presentationMode.wrappedValue.dismiss()
    } catch let err{
        print(err.localizedDescription)
        }
}

private func deleteGoal(){ //// < -- Here it works
    if let goal = goalItem {
        context.delete(goal)
    do{
        try context.save()
        presentationMode.wrappedValue.dismiss()
    }catch let err{
        print(err.localizedDescription)
        }
  }
}
}

推荐答案

按如下方式更改删除方法

private func deleteGoal(goal: NewGoal){ 
        context.delete(goal)
    do{
        try context.save()
        presentationMode.wrappedValue.dismiss()
    }catch{
        print(error)
    }
}

并将您的按钮更改为此

Button(action: {
    deleteGoal(goal: item)
}){
   Text("Delete") } 

这篇关于如何删除核心数据SwiftUI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆