swift - 更新 UIHostingConfiguration 中的@FocusState

标签 swift swiftui ios16

我正在使用 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/

相关文章:

ios - 如何在 Watchkit 中的 GlanceController 和 InterfaceController 之间进行通信?

swift - 在 List 中展开 HStack 以从头到尾,但不是从上到下,因此看起来项目之间有更宽的空间

swiftui - 根据窗口高度扩展 NSViewRepresentable (NSTextView) 高度

swift - 如何在 SwiftUI 中访问父框架

swiftui - UICalendarView 与 SwiftUI DatePicker NavigationSplitView 侧边栏中的尺寸错误

ios - 一次所有 View 的 NSNotification

ios - Xcode:WebView 在 endRefreshing() 之后刷新/重新加载

ios - 如何将数组对象转换为 JSON 字符串。苹果8. swift 1.2

swift - 将 UIEditMenuInteraction 与 UITextView 结合使用

swift - 添加图层后,播放按钮不会出现在 AVPlayer 中 - iOS 16