With <KMMViewModel>, how do I bind a SwiftUI TextF...
# multiplatform
l
With KMMViewModel, how do I bind a SwiftUI TextField to a
viewModel.text
value containing the text to be displayed?
r
You can use/create bindings to any mutable property with the
$
sign. E.g.
$viewModel.text
l
But I have to mark
viewModel.text
as
@State
for this, right?
Hmm, in my data model
viewModel.text
is a
val
, because the uiState gets copied everytime
Actually the state is in a data class
Copy code
data class UiState(
    val text: String,
    //... other properties
)
r
So what does your text property in the viewmodel look like?
l
Sorry, I should have been more specific. The viewModel emits
uiState
, the
uiState
contains the
text
property.
r
So to get the value you would have to call
viewModel.uiState.text
correct?
l
Yes
image.png
r
Hmm in that case I don't think there is a built-in way to get a binding. A generic way to get a binding isn't straightforward either since it would have to call the
copy
function with the correct parameter.
l
OK
I worked around this by creating a local var
transactionId
annotated with
@State
and assigning to it
viewModel.uiState.transactionId
r
Yeah that would work for SwiftUI. But any updates to the value wouldn't be accessible by the viewmodel or other code outside the view.
This is an interesting challenge. I might take a better look at it later to see if a generic approach is doable
l
Thank you for your quick help!
j
You might have to make a custom Binding that wraps your state and handles calling your method. I have to do this since I am using an MVI framework with unidirectional data flow...
Copy code
Binding<String>(
  get: { viewModel.uiState.transactionId }
  set: { viewModel.setTransactionId($0) }
)
l
Thank you so much!
j
Example of it here as well fwiw (though using Decompose instead of KMMViewModel in this example) https://github.com/joreilly/Confetti/blob/main/iosApp/iosApp/Sessions/SessionListView.swift
thank you color 1
👍 1
j
@John O'Reilly Line 71?
j
yes, exactly