Hello! I'm working with the UIHostingConfiguration and would like to set a Toolbar for a TextField which I placed in the content. I've tried to set ToolbarRole and Toolbar Visibility. Unfortunately, it doesn't work. Here's my example code:
Cell:
cell.configurationUpdateHandler = { (cell, state) in
cell.contentConfiguration = UIHostingConfiguration {
RowView(item: item)
}
}
View:
@ObservedObject var item: Movie
var body: some View {
TextField("Title", text: $item.title)
.toolbar(content: {
ToolbarItem(placement: .keyboard) {
Button("Confirm", action: {})
}
})
.toolbar(.visible, in: .automatic)
}
}
The .toolbar
modifier is not supported inside UIHostingConfiguration
. This is because the SwiftUI toolbar API requires a connection to the view controller hierarchy in UIKit, and UIHostingConfiguration
does not interface with any UIViewController
in the UIKit part of your app.
You need to use UIHostingController
in order to use features in SwiftUI that rely on a connection to the view controller hierarchy in UIKit, including any SwiftUI view that relies on UIViewControllerRepresentable
internally. You can learn more about the differences between UIHostingConfiguration
and UIHostingController
in the Use SwiftUI with UIKit video from WWDC22.
If you have a need to use view controller dependent feature(s) of SwiftUI inside of a collection or table view cell, you may need to continue using UIKit to implement that specific cell instead, since UIHostingController
is not supported inside of cells. There is nothing wrong with using a mix of cells implemented with SwiftUI (using UIHostingConfiguration
) and cells implemented purely with UIKit in the same collection or table view — just remember to use separate cell registrations (or reuse identifiers) for different types of cells.