Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @FocusState with view models?

Tags:

swiftui

I'm using view models for my SwiftUI app and would like to have the focus state also in the view model as the form is quite complex.

This implementation using @FocusState in the view is working as expected, but not want I want:

import Combine
import SwiftUI

struct ContentView: View {
    @ObservedObject private var viewModel = ViewModel()
    @FocusState private var hasFocus: Bool

    var body: some View {
        Form {
            TextField("Text", text: $viewModel.textField)
                .focused($hasFocus)
            Button("Set Focus") {
                hasFocus = true
            }
        }
    }
}

class ViewModel: ObservableObject {
    @Published var textField: String = ""
}

How can I put the @FocusState into the view model?

like image 945
G. Marc Avatar asked Dec 14 '25 00:12

G. Marc


2 Answers

Assuming you have in ViewModel as well

class ViewModel: ObservableObject {
  @Published var hasFocus: Bool = false

  ...
}

you can use it like

struct ContentView: View {
    @ObservedObject private var viewModel = ViewModel()
    @FocusState private var hasFocus: Bool

    var body: some View {
        Form {
            TextField("Text", text: $viewModel.textField)
                .focused($hasFocus)
        }
        .onChange(of: hasFocus) {
           viewModel.hasFocus = $0     // << write !!
        }
        .onAppear {
           self.hasFocus = viewModel.hasFocus    // << read !!
        }
    }
}

as well as the same from Button if any needed.

like image 145
Asperi Avatar answered Dec 16 '25 00:12

Asperi


Create a @Published var hasFocus: Bool in the ViewModel and sync it:

    Form
        ...
        .onAppear { self.hasFocus = viewModel.hasFocus}
        .onChange(of: hasFocus) { viewModel.hasFocus = $0 }
        .onChange(of: viewModel.hasFocus) { hasFocus = $0 }
like image 20
Jano Avatar answered Dec 16 '25 01:12

Jano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!