I'm working with new feature in iOS 16: UIHostingConfiguration. In a content view I put a TextField. I try to manage the TextField's focus. To do that, I've created a @FocusState var. Unfortunately, I can't update .wrappedValue - the wrapped value always is false. Here's my code:
Cell:
cell.configurationUpdateHandler = { [self] (cell, state) in
cell.contentConfiguration = UIHostingConfiguration {
TaskView(task: task, shouldFocus: focusedTask == task)
}
}
View:
struct TaskView: View {
@ObservedObject var task: Task
@FocusState var shouldFocus: Bool
init(task: Task, shouldFocus: Bool) {
self.task = task
self.$shouldFocus.wrappedValue = shouldFocus
print($shouldFocus)
}
var body: some View {
HStack() {
Button("END") {
$shouldFocus.wrappedValue = false
}
TextField("Task", text: $task.title)
.focused($shouldFocus)
}
}
}
CodePudding user response:
When updating @FocusState
you don't need to use $
& wrappedValue
, simply replace this: $shouldFocus.wrappedValue = shouldFocus
with the following:
self.shouldFocus = shouldFocus//or false
CodePudding user response:
The FocusState
does not work that way, it is like State
but does not have init with initial value, so possible approach is as follows:
struct TaskView: View {
@ObservedObject var task: Task
var shouldFocus: Bool // << interface
@FocusState private var inFocus: Bool // << internal
init(task: Task, shouldFocus: Bool) {
self.task = task
self.shouldFocus = shouldFocus
}
var body: some View {
HStack() {
Button("END") {
inFocus = false
}
TextField("Task", text: $task.title)
.focused($inFocus)
}
.onAppear {
self.inFocus = shouldFocus // << here !!
}
}
}