SwiftUI Picker with selection as struct - swift

Iam trying to use Picker as selection of struct. Let say I have a struct "Pet" like below
struct Pet: Identifiable, Codable, Hashable {
let id = UUID()
let name: String
let age: Int
}
I am getting all Pet's from some class, where Pets are defined as #Published var pets = Pet
static let pets = Class().pets
I would like to be able to write a selection from picker to below variable:
#State private var petSelection: Pet?
Picker is:
Picker("Pet", selection: $petSelection){
ForEach(Self.pets) { item in
Text(item.name)
}
}
Picker shows properly all avaliavble pets but when I chose one petSelection has been not changed (nil). How should I mange it?
Thanks!
Edit:
Of course I know that I can use tag like below:
Picker("Pet", selection: $petSelection) {
ForEach(0 ..< Self.pet.count) { index in
Text(Self.pet[index].name).tag(index)
}
But wonder is it possible to use struct as selection. Thanks

Short answer: The type associated with the tag of the entries in your Picker (the Texts) must be identical to the type used for storing the selection.
In your example: You have an optional selection (probably to allow "empty selection") of Pet?, but the array passed to ForEach is of type [Pet]. You have to add therefore a .tag(item as Pet?) to your entries to ensure the selection works.
ForEach(Self.pets) { item in
Text(item.name).tag(item as Pet?)
}
Here follows my initial, alternate answer (getting rid of the optionality):
You have defined your selection as an Optional of your struct: Pet?. It seems that the Picker cannot handle Optional structs properly as its selection type.
As soon as you get rid of the optional for example by introducing a "dummy/none-selected Pet", Picker starts working again:
extension Pet {
static let emptySelection = Pet(name: "", age: -1)
}
in your view initialise the selection:
#State private var petSelection: Pet = .emptySelection
I hope this helps you too.

You use the following way:
#Published var pets: [Pet?] = [ nil, Pet(name: "123", age: 23), Pet(name: "123dd", age: 243),]
VStack{
Text(petSelection?.name ?? "name")
Picker("Pet", selection: $petSelection){
ForEach(Self.pets, id: \.self) { item in
Text(item?.name ?? "name").tag(item)
}}}

the type of $petSelection in Picker(selection:[...] has to be the same type of id within your struct.
So in your case you would have to change $petSelection to type if UUID since your items within the collection have UUID as identifier.
Anyway since this is not what you're after, but your intention is to receive the Pet as a whole when selected. For that you will need a wrapper containing Pet as the id. Since Pet is already Identifiable, there're only a few adjustments to do:
Create a wrapper having Pet as an id
struct PetPickerItem {
let pet: Pet?
}
Now wrap all collection items within the picker item
Picker("Pet", selection: $petSelection) {
ForEach(Self.pets.map(PetPickerItem.init), id: \.pet) {
Text("\($0.pet?.name ?? "None")")
}
}
You can now do minor adjustments like making PetPickerItem identifiable to remove the parameter id: from ForEach.
That's the best solution I came up with.

This is how I do it:
struct Language: Identifiable, Hashable {
var title: String
var id: String
}
struct PickerView: View {
var languages: [Language] = [Language(title: "English", id: "en-US"), Language(title: "German", id: "de-DE"), Language(title: "Korean", id: "ko-KR")]
#State private var selectedLanguage = Language(title: "German", id: "de-DE")
var body: some View {
Picker(selection: $selectedLanguage, label: Text("Front Description")) {
ForEach(self.languages, id: \.self) {language in
Text(language.title)
}
}
}

Related

Making struct conform to Identifiable crashes app

EDITS:
removed id: \.self
removed .onDelete from List (mistake in editing)
removed removeRows function
change the Note struct to only hash the id
I am making an app in swiftUI that returns a list of notes. I have a struct, note, that is defined as follows:
struct Note: Identifiable, Hashable {
let id = UUID()
var title: String
var content: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
It conforms to Identifiable so that it can be selected inside a List, and it conforms to Hashable so that it can be held inside a Set (for selection).
My view that (I think) is being super slow and eventually crashing is as follows:
struct SearchView: View {
#State private var searchValue: String = ""
#State private var searchResults: [Note] = [
Note(title: "Hi", content: "whats up"),
Note(title: "wassup", content: "hi")
]
#State private var selectKeeper = Set<Note>()
var body: some View {
VStack(alignment: .leading) {
SearchInputView(searchValue: $searchValue, searchResults: $searchResults)
List(searchResults, selection: $selectKeeper) { note in
Text(note.title )
}
}
}
}
SearchInputView is basically just a view that uses combine to run this function on the contents of a textfield every keypress:
func findIn(notes: [Note], pattern: String) -> [Note] {
if pattern.isEmpty { return notes }
var matchedNotes: [Note] = []
for note in notes {
let note = Note(title: note.title.uppercased(), content: note.content.uppercased())
let pattern = pattern.uppercased()
if note.title.contains(pattern) || note.content.contains(pattern) {
matchedNotes.append(note)
}
}
return matchedNotes
}
This all used to work fine with a ForEach loop and the Note struct not conforming to Identifiable, but right now for whatever reason, the app crashes as soon as I type anything into the text box. I have no idea why this is happening, and I can't see anything in the profilers that might tell me what's going on. The only thing is that as soon as I type all of the uses goes up to 100% and the app crashes. Any ideas?
Thanks!
I figured out that my problem was due to putting the findIn function outside of the struct that was using it. I am not at all sure why this is, but putting it inside of the struct calling it caused it to work out fine. Thanks so much to everyone who provided helpful suggestions in the comments!

How do you handle dynamic column names in a SwiftUI Table on Mac

I have a SwiftUI table that I need to layout based on some request data from a server. This data is dynamic and changes. However, once I read this data into an array, it will not allow me to do a forEach on the column data, as it companies about not conforming to "TableColumnContent". Is there another way to loop this creation, or is there a simple way to conform to this protocol? I am having trouble understanding that protocol when I look at it.
struct DataProperty : Identifiable
{
var id: String
var name: String
}
struct TableDataView : View
{
#EnvironmentObject var cache: ServerCache
var body: some View
{
Table(cache.activeTableData)
{
ForEach(cache.activeProperties, id: \.self) {property in
TableColumn(property.name, value: \.id)
}
}
}
}
Note that activeProperties is an array of DataProperty. What am I doing wrong here?

Binding to subscript doesn't update TextField (macOS)

I have this Store struct, which is a wrapper for all my data. It has a subscript operator which takes in a UUID, and returns the associated object.
This way, I can have a List bind to a selection variable, which has type UUID, and then in another view I can access the selected object from that UUID.
However, I'm experiencing an issue where my TextField which binds to the Store doesn't update. It does update if I wrap it in another Binding, or if I instead just use Text.
Here is an minimal reproducible example:
struct Person: Identifiable, Hashable {
let id = UUID()
var name: String
}
struct Store {
var data: [Person]
subscript(id: Person.ID) -> Person {
get {
data.first(where: { $0.id == id })!
}
set {
data[data.firstIndex(where: { $0.id == id })!] = newValue
}
}
}
struct ContentView: View {
#State var store = Store(data: [
Person(name: "Joe"),
Person(name: "Eva"),
Person(name: "Sam"),
Person(name: "Mary")
])
#State var selection: Person.ID?
var body: some View {
NavigationView {
List(store.data, selection: $selection) {
Text($0.name)
}
if let selection = selection {
// Creating a new Binding which simply wraps $store[selection].name
// fixes this issue. Or just using Text also works.
TextField("Placeholder", text: $store[selection].name)
}
else {
Text("No Selection")
}
}
}
}
To reproduce this issue, just click different names on the Sidebar. For some reason the detail view's TextField doesn't update!
This issue can also be resolved if we simply move the Store to a ObservableObject class with #Published.
Also, making the Store conform to Hashable doesn't help this issue.
I feel like I'm missing something very basic with SwiftUI. Is there any way to fix this?
EDIT:
I've changed out Store for an [Person], and I made an extension with the same subscript operator that is in Store. However, the problem still remains!
try this:
TextField("Placeholder", text: $store[selection].name)
.id(selection) // <-- here

Use an object to collect form data and set default value in Swift

I'm brand new in Swift development, and I can't for the life of me figure this out. All I want to do is use an object to collect a forms data, save it to Realm, and then send it to the server via API.
In every example I've found, people are creating a new State variable for each element in their form. This seems unpractical for forms with many fields, so I tried to just create an object with properties that match the form fields I need. If I don't try to set any default values, this works as I expect. But when I try to set some default values for the form in the init(), I get errors that I don't know how to resolve. Here's some partial code:
The object that will be used to collect the form data:
class RecordObject: ObservableObject {
var routeId: Int?
var typeId: Int?
var inDate: Date?
var outDate: Date?
var nextDate: Date?
// .... more properties
}
And what I want to do is in the View, set some default values in the init() that need some logic to derive the value:
In the View:
struct AddLauncherView: View {
var route: Route // this is passed from a previous view that lists all the routes
#StateObject var record: RecordObject = RecordObject() // this is where I want to store all the form data
init(){
_record.routeId = self.route.id // I get the error: Referencing property 'routeId' requires wrapped value of type 'RecordObject'
self.record.inDate = Date() // this gives the error: 'self' used before all stored properties are initialized
//self.record.nextDate = here I need to do some date math to figure out the next date
}
var body: some View {
Form{
DatePicker("In Date", selection: $record.inDate, displayedComponents: .date)
// .... more form elements
}
}
}
I know I could add default values in the RecordObject class, but there are some properties that will need some logic to assign the default value.
Can someone help out a Swift noob and give me some pointers for making this work? Do I really need to create a State var for each form field in the View?
If you did use a class (ObservableObject), you'd want the properties to be annotated with #Published. However, it's probably a better idea to use a struct with a #State variable that contains all of the various properties you need. That may look like this:
struct Record {
var routeId: Int?
var typeId: Int?
var inDate: Date?
var outDate: Date?
var nextDate: Date?
}
struct AddLauncherView: View {
var route: Route
#State var record: Record
init(route: Route) {
self.route = route
_record = State(initialValue: Record(routeId: route.id,
typeId: nil,
inDate: Date(),
outDate: nil,
nextDate: nil))
}
var body: some View {
Form{
DatePicker("In Date",
selection: Binding<Date>(get: {record.inDate ?? Date()},
//custom binding only necessary if inDate is Date? -- if you make it just Date, you can bind directly to $record.inDate
set: {record.inDate = $0}),
displayedComponents: .date)
// .... more form elements
}
}
}
You are using the ObservableObject incorrectly. You data model should be a struct, and then the class publishes values that are of the type of the struct, so:
struct Record: Identifiable {
// First, save yourself some grief later and make it conform to Identifiable
let id = UUID()
// The listed variables are probably non-optional in your data model.
// If they are optional, mark them as optional, otherwise
var routeId: Int
var typeId: Int
var inDate: Date
// These are more likely optional
var outDate: Date?
var nextDate: Date?
// .... more properties
}
class RecordObject: ObservableObject {
// Make the source of truth #Published so things are updated in your view
#Published var records: [Record] = []
// OR use an init
#Published var records: [Record]
init(records: [Records] {
self.records = records
// or call some function that imports/creates the records...
}
}

SwiftUI ForEach Binding compile time error looks like not for-each

I'm starting with SwiftUI and following WWDC videos I'm starting with #State and #Binding between two views. I got a display right, but don't get how to make back-forth read-write what was not include in WWDC videos.
I have model classes:
class Manufacturer {
let name: String
var models: [Model] = []
init(name: String, models: [Model]) {
self.name = name
self.models = models
}
}
class Model: Identifiable {
var name: String = ""
init(name: String) {
self.name = name
}
}
Then I have a drawing code to display that work as expected:
var body: some View {
VStack {
ForEach(manufacturer.models) { model in
Text(model.name).padding()
}
}.padding()
}
and I see this:
Canvas preview picture
But now I want to modify my code to allows editing this models displayed and save it to my model #Binding so I've change view to:
var body: some View {
VStack {
ForEach(self.$manufacturer.models) { item in
Text(item.name)
}
}.padding()
}
But getting and error in ForEach line:
Generic parameter 'ID' could not be inferred
What ID parameter? I'm clueless here... I thought Identifiable acting as identifier here.
My question is then:
I have one view (ContentView) that "holds" my datasource as #State variable. Then I'm passing this as #Binding to my ManufacturerView want to edit this in List with ForEach fill but cannot get for each binding working - how can I do that?
First, I'm assuming you have something like:
#ObservedObject var manufacturer: Manufacturer
otherwise you wouldn't have self.$manufacturer to begin with (which also requires Manufacturer to conform to ObservableObject).
self.$manufacturer.models is a type of Binding<[Model]>, and as such it's not a RandomAccessCollection, like self.manufacturer.models, which is one of the overloads that ForEach.init accepts.
And if you use ForEach(self.manufacturer.models) { item in ... }, then item isn't going to be a binding, which is what you'd need for, say, a TextField.
A way around that is to iterate over indices, and then bind to $manufacturer.models[index].name:
ForEach(manufacturer.indices) { index in
TextField("model name", self.$manufacturer.models[index].name)
}
In addition to that, I'd suggest you make Model (and possibly even Manufacturer) a value-type, since it appears to be just a storage of data:
struct Model: Identifiable {
var id: UUID = .init()
var name: String = ""
}
This isn't going to help with this problem, but it will eliminate possible issues with values not updating, since SwiftUI wouldn't detect a change.