UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

1      

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"
        }
    }
}

1      

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

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.