WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Need help splicing a view together

Forums > SwiftUI

I'm trying to splice some code I found into a current SwiftUI view I have.

Basically, I want to make my segmented picker have colors that correspond to priority colors in a to-do list view.

Here is the sample code for the colored segmented picker. (Taken from HWS)

import SwiftUI

enum Colors: String, CaseIterable{
    case red, yellow, green, blue

    func displayColor() -> String {
        self.rawValue.capitalized
    }
}

struct TestView: View {
    @State private var selectedColor = Colors.red

    var body: some View {
        Picker(selection: $selectedColor, label: Text("Colors")) {
            ForEach(Colors.allCases, id: \.self) { color in
                Text(color.displayColor())
            }
        }
        .padding()
        .colorMultiply(color(selectedColor))
        .pickerStyle(SegmentedPickerStyle())
    }

    func color(_ selected: Colors) -> Color {
        switch selected {
        case .red:
            return .red
        case .yellow:
            return .yellow
        case .green:
            return .green
        case .blue:
            return .blue
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

Then, here is the (complete because I don't have the chops to make MRE's yet– I'm still learning) code for the to-do list view (Taken from YouTube– I can't remember the creator's name, but I'll post it below once I find it again.):

import SwiftUI

enum Priority: String, Identifiable, CaseIterable {

    var id: UUID {
        return UUID()
    }

    case one = "Priority 1"
    case two = "Priority 2"
    case three = "Priority 3"
    case four = "Priority 4"
}

extension Priority { //"priority.title"

    var title: String {
        switch self {

            case .alloc:
                return "Priority 1"
            case .aoc:
                return "Priority 2"
            case .charting:
                return "Priority 3"
            case .clinical:
                return "Priority 4"
        }
    }
}

struct ToDoView: View {
    @State private var title: String = ""
    @State private var selectedPriority: Priority = .charting
    @FocusState private var isTextFieldFocused: Bool
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(entity: Task.entity(), sortDescriptors: [NSSortDescriptor(key: "dateCreated", ascending: true)]) private var allTasks: FetchedResults<Task>

    private func saveTask() {

        do {
            let task = Task(context: viewContext)
            task.title = title
            task.priority = selectedPriority.rawValue
            task.dateCreated = Date()
            try viewContext.save()
        } catch {
            print(error.localizedDescription)
        }

    }

    private func styleForPriority(_ value: String) -> Color {
        let priority = Priority(rawValue: value)

        switch priority {
            case .one:
                return Color.green
            case .two:
                return Color.red
            case .three:
                return Color.blue
            case .four:
                return Color.yellow
            default:
                return Color.black
        }
    }

    private func updateTask(_ task: Task) {

        task.isFavorite = !task.isFavorite

        do {
            try viewContext.save()
        } catch {
            print(error.localizedDescription)
        }
    }

    private func deleteTask(at offsets: IndexSet) {
        offsets.forEach { index in
            let task = allTasks[index]
            viewContext.delete(task)

            do {
                try viewContext.save()
            } catch {
                print(error.localizedDescription)
            }
        }
    }

    var body: some View {
        NavigationView {
            VStack {
                TextField("Enter task...", text: $title)
                    .textFieldStyle(.roundedBorder)
                    .focused($isTextFieldFocused)
                    .foregroundColor(Color(UIColor.systemBlue))
                    .modifier(TextFieldClearButton(text: $title))
                    .multilineTextAlignment(.leading)
                Picker("Type", selection: $selectedPriority) {
                    ForEach(Priority.allCases) { priority in
                        Text(priority.title).tag(priority)
                    }
                }.pickerStyle(.segmented)

                Button("Save") {
                    saveTask()
                }
                .padding(10)
                .frame(maxWidth: .infinity)
                .background(Color.blue)
                .foregroundColor(.white)
                .clipShape(RoundedRectangle(cornerRadius: 10.0, style: .continuous))

                List {

                    ForEach(allTasks) { task in
                        HStack {
                            Circle()
                                .fill(styleForPriority(task.priority!))
                                .frame(width: 15, height: 15)
                            Spacer().frame(width: 20)
                            Text(task.title ?? "")
                            Spacer()
                            Image(systemName: task.isFavorite ? "checkmark.circle.fill": "circle")
                                .foregroundColor(.red)
                                .onTapGesture {
                                    updateTask(task)
                                }
                        }
                    }.onDelete(perform: deleteTask)
                }
                Spacer()
            }
            .padding()
            .navigationTitle("To-Do List")
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button(action: {
                        isTextFieldFocused = false

                    }) { Text("Done")}

                }
            }
        }
    }
}

Appreciate any help. Thanks!

   

Just a note that this is not correct

enum Priority: String, Identifiable, CaseIterable {

    var id: UUID {
        return UUID()
    }

    case one = "Priority 1"
    case two = "Priority 2"
    case three = "Priority 3"
    case four = "Priority 4"
}

extension Priority { //"priority.title"

    var title: String {
        switch self {

            case .alloc:                      // Type 'Priority' has no member `alloc`
                return "Priority 1" 
            case .aoc:                        // Type 'Priority' has no member `aoc`
                return "Priority 2"
            case .charting:                // Type 'Priority' has no member `charting`
                return "Priority 3"
            case .clinical:                  // Type 'Priority' has no member `clinical`
                return "Priority 4"
        }
    }
}

So this do not work as the case for Priority is one, two, three, four and not alloc, aoc, charting, clinical may be shouuld be like this

enum Priority: String, Identifiable, CaseIterable {
    var id: UUID {
        UUID()
    }

    case alloc = "Priority 1"
    case aoc = "Priority 2"
    case charting = "Priority 3"
    case clinical = "Priority 4"
}

extension Priority { //"priority.title"
    var title: String {
        switch self {
            case .alloc:
                return "Priority 1"
            case .aoc:
                return "Priority 2"
            case .charting:
                return "Priority 3"
            case .clinical:
                return "Priority 4"
        }
    }
}

   

Yep. I just realized that I copied an earlier revision of the code. That's fixed in the production version.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.