gpt4 book ai didi

swift - 如何删除核心数据 SwiftUI?

转载 作者:行者123 更新时间:2023-12-04 07:22:03 25 4
gpt4 key购买 nike

很抱歉这个愚蠢的问题,但我两天来一直在寻找答案,并尝试了很多方法来处理它。

我的 WatchOS 应用在 Core Data 上运行。那里有 3 个 View :

  1. FirstView - 带有用于添加新目标和已添加目标列表的按钮的 View 。
  2. AddGoalView - 在按下添加新目标后出现。
  3. RingView - 带有目标环(类似于事件环机制)和所有数据的 View 。

因此,我试图让用户有机会直接在 FirstView 上删除创建的目标。经过不同的迭代,我了解到删除按钮在 RingView 中起作用,但在第一 View 。您能否就此问题发表您的看法(如果可以,请提供 .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") }

关于swift - 如何删除核心数据 SwiftUI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68432307/

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