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

SOLVED: Class & struct -> Segmented Picker Style?

Forums > SwiftUI

How am I going to explain this one...

Okay, I have the following class and struct set up, and updated the environment variables in SceneDelegate too:

class PointsTables: ObservableObject {
    @Published var taskdata: [PointsTable] = []
}

struct PointsTable: Identifiable, Hashable {
    var id = UUID()
    var recordID: CKRecord.ID?
    var task: String
    var stretch: Int
    var achievable: Int
}

I pull the data from CloudKit database which contains as task, stretch and achievable values.

In my view, i have this:

    @EnvironmentObject var listTasks: PointsTables

Now I want to create a Picker with SegmentedPickerStyle, that creates just the task string from the Struct, eg:

Picker(selection: $taskSelector, label: Text("What task?")
                ) {
                    ForEach(listTasks.taskdata) { index in
                        Text(index.task)
                    }
                }.padding(.bottom)
                 .pickerStyle(SegmentedPickerStyle())
                 .labelsHidden()

But this gives me a Segmented Picker, but no selection, as I can't work out how to do the ForEach with an index (which I don't think has one).

Anyone offer some advice? I feel I'm close to the solution, yet miles away.

3      

By "ForEach with an index" do you mean using a range, as in ForEach (0 ..< tasks.count)? Why do you think you need that? Because your taskSelector is an index? Can it be the data itself?

Your ForEach returns index, which is a piece of data, not an actual index from the range. Your taskSelector needs to be that type and equal to the selection you want.

3      

Thanks for the suggestion. With a new view on my approach, I did persevere with my code. In the end, i found:

listTasks.taskdata[index].task 

was the format I was looking for in the end, and now have a succesful picker. I also learnt by putting the Picker in it's own struct view and calling it, prevented the slight flicker you see as iOS refreshes the view. Good tips. Thanks

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.