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

Not sure how to get a Bool value in a table to update when it changes

Forums > SwiftUI

@Tut  

Trying to learn Swift and SwiftUI, but I'm not happy about it.

I have a data model:

class File : Identifiable, Hashable, CustomStringConvertible {
    var edited:Bool = false;
}

The SwiftUI view has a column that shows the edited value as either blank or the pencil system image:

public var body: some View {
  NavigationSplitView {
    Table(of:File.self, selection:$selection) { 
      TableColumn("Edited") { fyl in
        if fyl.edited {
          SwiftUI.Label("", systemImage:"pencil")
            .font(.system(size:8, weight:.heavy))
        }
      }
    }
  rows: { 
  etc…

However, when an edited value is set to true, the table doesn't update. I have to manually click on the row to make it redraw. Since SwiftUI doesn't have the convenience of letting me assign the Table to a property and then calling reloadData like NSTableView does, I'm not sure what to do. I've read things about @ObservableObject and such, but I'm not sure I understand where it goes, and when I try it on the edited property I get a syntax error. Any help?

   

@Tut  

That's a little helpful, but not enough. I've added ObservableObject to the File class. According to Apple's docs, the edited property needs to be marked with @Published. In my case, the View has a var that is an array of File. When I annotate that var with either @StateObject (or any of the @xxx wrappers or whatever they are), it produces errors. Apple's docs also show an example for a single object of the class, not an array.

class File : Identifiable, Hashable, CustomStringConvertible, ObservableObject {
    @Published var          edited:Bool = false;
}
public var body: some View {
     /*What goes here?*/var         files:[File] = [];
     The rest as above…

   

@Tut  

I wish I could just get an answer without having to watch a video. Maybe I misunderstood the purpose of this forum, but I assumed I could ask a question and get some plain answers or clear cut suggestions. I'm not trying to start a new career as a Swift engineer, but just finish a small project by dabbling in SwiftUI to see what all the hubbub is about.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

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.