Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created February 10, 2024 16:29
Show Gist options
  • Save christianselig/32bd8742500a7ed9f35f78406a89c16e to your computer and use it in GitHub Desktop.
Save christianselig/32bd8742500a7ed9f35f78406a89c16e to your computer and use it in GitHub Desktop.

I have a view model with two properties, a number and a selection. The number is updated once per second and shown on screen.

Beside that on the screen, is a Menu that displays the selection on click. But even though the Menu selection is not updated/affected once per second, the number is, and that seems to break the Menu's highlight state. In fact, it happens even if I put the selection in a separate object all together.

Why is this? How do I make SwiftUI more selective in only updating what's relevant?

struct ContentView: View {
    @State var viewModel = ViewModel(number: 111_111, animal: "Horse")
    
    let animals = ["Goat", "Pig", "Horse", "Cow", "Sheep"]
    
    var body: some View {
        ZStack {
            HStack {
                Text("#\(viewModel.number)")
                    .monospacedDigit()
                
                Menu {
                    Picker("Select an animal", selection: $viewModel.animal) {
                        ForEach(animals, id: \.self) {
                            Text($0)
                        }
                    }
                } label: {
                    Image(systemName: "ladybug.fill")
                }
            }
        }
    }
}

@Observable
class ViewModel {
    var number: Int
    var animal: String
    
    init(number: Int, animal: String) {
        self.number = number
        self.animal = animal
        
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.number = (100_000 ... 1_000_000).randomElement()!
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment