将int保存到核心数据swiftui

发布于 2025-01-24 06:21:20 字数 4598 浏览 2 评论 0原文

以下是我的任务管理应用程序中的视图,我试图在选择时将其显示一定的颜色。我的问题是,如何在核心数据中保存用于优先级和颜色选择器的INT?我不知道如何将int值转换为int32,并且它不能以int32对象的形式启动,因为那样它将无法用作每个选择器的背景颜色的选择器。请帮忙!

struct NewTask: View {
    @Environment(\.dismiss) var dismiss
    
    // MARK: Task Values
    @State var taskTitle: String = ""
    @State var taskDescription: String = ""
    @State var taskDate: Date = Date()
    
    var colors = ["Teal","Yellow","Pink"]
    @State var selectedColor: Int = 0
    
    var colorsColors = ["logoTeal","logoYellow","logoPink"]
    
    var selectedColorInt: String {
        get {
            return ("\(selectedColor)")
        }
    }
    
    var priorities = ["Urgent","Slightly Urgent","Not Urgent"]
    @State var selectedPriority: Int = 0
    
    
    var priorityColors = ["priorityRed","priorityYellow","priorityGreen"]

    
    // MARK: Core Data Context
    @Environment(\.managedObjectContext) var context
    
    @EnvironmentObject var taskModel: TaskViewModel
    var body: some View {
        
        NavigationView{
            List{
                Section {
                    TextField("Go to work", text: $taskTitle)
                    Picker("Priority", selection: $selectedPriority) {
                        ForEach(0..<priorities.count){
                            Text(priorities[$0])
                        }
                        .padding(5)
                        .foregroundColor(.white)
                        .background(priorityColors[selectedPriority])
                        .cornerRadius(5)
                        
                    }
                    Picker("Theme", selection: $selectedColor) {
                        ForEach(0..<colors.count){
                            Text(colors[$0])
                        }
                        .padding(5)
                        .foregroundColor(.black)
                        .background(colorColors[selectedColor])
                        .cornerRadius(5)
                    }
                } header: {
                    Text("Task Information")
                }

                Section {
                    TextEditor(text: $taskDescription)
                } header: {
                    Text("Task Description")
                }
                
                // Disabling Date for Edit Mode
                if taskModel.editTask == nil{
                    
                    Section {
                        DatePicker("", selection: $taskDate)
                            .datePickerStyle(.graphical)
                            .labelsHidden()
                    } header: {
                        Text("Task Date")
                    }
                }
            }
            .listStyle(.insetGrouped)
            .navigationTitle("Add New Task")
            .navigationBarTitleDisplayMode(.inline)
            // MARK: Disbaling Dismiss on Swipe
            .interactiveDismissDisabled()
            // MARK: Action Buttons
            .toolbar {
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save"){
                        
                        if let task = taskModel.editTask{
                            
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                        }
                        else{
                            let task = Task(context: context)
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                            task.taskDate = taskDate
                            /*task.selectedColor = selectedColor*/
                            /*task.selectedPriority = selectedPriority*/
                        }
                        
                        // Saving
                        try? context.save()
                        // Dismissing View
                        dismiss()
                    }
                    .disabled(taskTitle == "" || taskDescription == "")
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel"){
                        dismiss()
                    }
                }
            }
            // Loading Task data if from Edit
            .onAppear {
                if let task = taskModel.editTask{
                    taskTitle = task.taskTitle ?? ""
                    taskDescription = task.taskDescription ?? ""
                }
            }
        }
    }
    
}

Below is a view within my Task management app, and I am trying to make my picker display a certain color when it is chosen. My question is how do I save the Ints used for the priority and color picker within Core data? I can't figure out how to convert the int value into int32, and it can't start as an Int32 object because then it wouldn't be able to be used as the selector for the background color of each picker. PLEASE HELP!

struct NewTask: View {
    @Environment(\.dismiss) var dismiss
    
    // MARK: Task Values
    @State var taskTitle: String = ""
    @State var taskDescription: String = ""
    @State var taskDate: Date = Date()
    
    var colors = ["Teal","Yellow","Pink"]
    @State var selectedColor: Int = 0
    
    var colorsColors = ["logoTeal","logoYellow","logoPink"]
    
    var selectedColorInt: String {
        get {
            return ("\(selectedColor)")
        }
    }
    
    var priorities = ["Urgent","Slightly Urgent","Not Urgent"]
    @State var selectedPriority: Int = 0
    
    
    var priorityColors = ["priorityRed","priorityYellow","priorityGreen"]

    
    // MARK: Core Data Context
    @Environment(\.managedObjectContext) var context
    
    @EnvironmentObject var taskModel: TaskViewModel
    var body: some View {
        
        NavigationView{
            List{
                Section {
                    TextField("Go to work", text: $taskTitle)
                    Picker("Priority", selection: $selectedPriority) {
                        ForEach(0..<priorities.count){
                            Text(priorities[$0])
                        }
                        .padding(5)
                        .foregroundColor(.white)
                        .background(priorityColors[selectedPriority])
                        .cornerRadius(5)
                        
                    }
                    Picker("Theme", selection: $selectedColor) {
                        ForEach(0..<colors.count){
                            Text(colors[$0])
                        }
                        .padding(5)
                        .foregroundColor(.black)
                        .background(colorColors[selectedColor])
                        .cornerRadius(5)
                    }
                } header: {
                    Text("Task Information")
                }

                Section {
                    TextEditor(text: $taskDescription)
                } header: {
                    Text("Task Description")
                }
                
                // Disabling Date for Edit Mode
                if taskModel.editTask == nil{
                    
                    Section {
                        DatePicker("", selection: $taskDate)
                            .datePickerStyle(.graphical)
                            .labelsHidden()
                    } header: {
                        Text("Task Date")
                    }
                }
            }
            .listStyle(.insetGrouped)
            .navigationTitle("Add New Task")
            .navigationBarTitleDisplayMode(.inline)
            // MARK: Disbaling Dismiss on Swipe
            .interactiveDismissDisabled()
            // MARK: Action Buttons
            .toolbar {
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save"){
                        
                        if let task = taskModel.editTask{
                            
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                        }
                        else{
                            let task = Task(context: context)
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                            task.taskDate = taskDate
                            /*task.selectedColor = selectedColor*/
                            /*task.selectedPriority = selectedPriority*/
                        }
                        
                        // Saving
                        try? context.save()
                        // Dismissing View
                        dismiss()
                    }
                    .disabled(taskTitle == "" || taskDescription == "")
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel"){
                        dismiss()
                    }
                }
            }
            // Loading Task data if from Edit
            .onAppear {
                if let task = taskModel.editTask{
                    taskTitle = task.taskTitle ?? ""
                    taskDescription = task.taskDescription ?? ""
                }
            }
        }
    }
    
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猥︴琐丶欲为 2025-01-31 06:21:20

这是我要采取的方法。

首先,由于优先级仅是三个值之一,因此将其表示为具有INT32原始值的枚举,并且文本描述和颜色作为枚举的属性:

enum Priority: Int32, CaseIterable {
    case urgent = 0
    case slightlyUrgent = 1
    case notUrgent = 2

    var description: String {
        switch self {
        case .urgent: return "Urgent"
        case .slightlyUrgent: return "Slightly Urgent"
        case .notUrgent: return "Not Urgent"
        }
    }

    var colorName: String {
        switch self {
        case .urgent: return "PriorityRed"
        case .slightlyUrgent: return "PriorityYellow"
        case .notUrgent: return "PriorityGreen"
        }
    }

    var color: Color { Color(colorName) }
}

以表单为单位,这使您的代码保持清洁,并且允许您通过0在初始化状态变量时使用语义值:

@State private var selectedPriority: Priority = .urgent

Picker("Priority", selection: $selectedPriority) {
  ForEach(Priority.allCases, id: \.self) { priority in
    Text(priority.description)
      .padding(5)
      .foregroundColor(.black)
      .background(priority.color)
      .cornerRadius(5)
  }
}

然后,将扩展名添加到Coredata模型中,该模型使其具有Pircipity属性,添加Getter和setter它使用存储的列:

extension Task {
  var priorityEnum: Priority {
    get { Priority(rawValue: priority) ?? .urgent }
    set { priority = newValue.rawValue }
  }
}

然后,将表单详细信息保存到核心数据管理的对象中时,您可以将task.priorityenum设置为Picker的值,并且自定义属性将确保正确int32值存储。

同样,当从任务加载编辑表单的状态变量时,引用task.priorityenum将使您pirctity值以数据库中存储的整数初始化。

Here's the approach I would take.

First, as priority will only ever be one of three values, express it as an enum with an Int32 raw value, and with the text description and colours as properties of the enum:

enum Priority: Int32, CaseIterable {
    case urgent = 0
    case slightlyUrgent = 1
    case notUrgent = 2

    var description: String {
        switch self {
        case .urgent: return "Urgent"
        case .slightlyUrgent: return "Slightly Urgent"
        case .notUrgent: return "Not Urgent"
        }
    }

    var colorName: String {
        switch self {
        case .urgent: return "PriorityRed"
        case .slightlyUrgent: return "PriorityYellow"
        case .notUrgent: return "PriorityGreen"
        }
    }

    var color: Color { Color(colorName) }
}

In the form, this keeps your code a bit cleaner, and allows you to use semantic values over 0 when initialising your state variable:

@State private var selectedPriority: Priority = .urgent

Picker("Priority", selection: $selectedPriority) {
  ForEach(Priority.allCases, id: \.self) { priority in
    Text(priority.description)
      .padding(5)
      .foregroundColor(.black)
      .background(priority.color)
      .cornerRadius(5)
  }
}

Then, add an extension to your CoreData model that gives it a Priority property, adding a getter and setter so that it uses the stored column:

extension Task {
  var priorityEnum: Priority {
    get { Priority(rawValue: priority) ?? .urgent }
    set { priority = newValue.rawValue }
  }
}

Then when it comes to save the form details into the Core Data managed object, you can set task.priorityEnum to the picker's value, and the custom property will make sure that the correct Int32 value is stored.

Likewise, when loading the edit form's state variables from the task, referencing task.priorityEnum will get you a Priority value initialized with the integer that's stored in the database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文