2

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?

G. Marc
  • 3,489
  • 3
  • 20
  • 40

1 Answers1

2

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.

Asperi
  • 173,274
  • 14
  • 284
  • 455
  • Thanks, this is basically working. But there's an issue which is not related to the view model solution per se. Setting hasFocus to true in the onAppear handler does not put the cursor into the text field at startup. Is this a SwiftUI bug? – G. Marc Nov 28 '21 at 07:30
  • Alright, found a thread targeting the issue mentioned in my previous comment: https://stackoverflow.com/questions/68073919/swiftui-focusstate-how-to-give-it-initial-value. It's a bit annoying that we need so many ugly workaround with SwiftUI... – G. Marc Nov 28 '21 at 07:39
  • Excellent solution! Thank you @Asperi – ixany Jan 24 '22 at 13:42