更新 SwiftUI 中的 inputAccessoryView (UIViewRepresentable)

问题描述

我想使用 SwiftUI 在键盘上方显示搜索结果。为此,我为 please provide nameadeel adeel a adeel b adeel c 创建了一个 UIViewRepresentable 并相应地设置了 UITextField

一切都显示正确,但 inputAccessoryView 没有更新。

inputAccessoryView

这就是我传递 struct V_ToolbarTextField<Content: View>: UIViewRepresentable { var title: String @Binding var text: String var keyType: UIKeyboardType var toolbarContent: Content init(_ title: String,text: Binding<String>,keyType: UIKeyboardType = .alphabet,toolbarContent: Content) { self.title = title self._text = text self.keyType = keyType self.toolbarContent = toolbarContent } func makeUIView(context: Context) -> UITextField { let textfield = UITextField() textfield.keyboardType = keyType textfield.placeholder = title let textUIKit = UIHostingController(rootView: toolbarContent) textUIKit.view.frame = CGRect(x: 0,y: 0,width: 800,height: 60) textfield.inputAccessoryView = textUIKit.view return textfield } func updateUIView(_ uiView: UITextField,context: Context) { uiView.text = text } } 内容的方式:

inputAccessoryView

我尝试绑定 V_ToolbarTextField("Title",text: $gameNameFilter,toolbarContent: viewContainingSearchResults()) 并在 toolbarContent 中设置 inputAccessoryView。我也尝试过创建一个 Coordinator 类并将 updateUIView() 的委托设置给它,希望使用 UITextField 函数来更新它,但我不知道是哪一个,我不是能够正确设置委托。

解决方法

我无法让它工作,并用底部的工具栏将 inputAccessoryView 丢弃为 VStack。显示键盘时我将其隐藏。

@State var keyboardOpen = false

VStack {
    
    // everything else...
    
    if (keyboardOpen) {
        V_FilteredGameList(filter: vm.gameName,action: { game in
            vm.setExistingGame(game: game)
            hideKeyboard()
        })
    }
}
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
        keyboardOpen = true
}
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
        keyboardOpen = false
}