我正在使用 iOS 16 中的新功能:UIHostingConfiguration。在内容 View 中,我放置了一个文本字段。我尝试管理 TextField 的焦点。为此,我创建了一个 @FocusState 变量。不幸的是,我无法更新 .wrappedValue - 包装值始终为 false。这是我的代码:
单元格:
cell.configurationUpdateHandler = { [self] (cell, state) in
cell.contentConfiguration = UIHostingConfiguration {
TaskView(task: task, shouldFocus: focusedTask == task)
}
}
查看:
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)
}
}
}
最佳答案
FocusState
不会那样工作,它类似于 State
但没有具有初始值的 init,因此可能的方法如下:
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 !!
}
}
}
关于swift - 更新 UIHostingConfiguration 中的@FocusState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72949478/