我目前正在尝试在UIViewControllerRepresentable中实现UITableViewController,其中单元格的内容再次是SwiftUI视图。我无法使用SwiftUI列表,因为我想稍后添加UISearchController。
因为我希望能够将自定义的SwiftUI视图放置在每个单元格的内容中,所以我没有其他选择,必须在单元格内使用SwiftUI视图。
我的当前代码如下,但不起作用:
class SearchableListCell: UITableViewCell {
let contentController: UIViewController
init(withContent content: UIViewController, reuseIdentifier: String) {
self.contentController = content
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.addSubview(self.contentController.view)
// Tried also
// self.contentView.addSubview(self.contentController.view)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct SearchableList: UIViewControllerRepresentable {
let data: [String]
var viewBuilder: (String) -> ContentView
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UITableViewController {
return context.coordinator.tableViewController
}
func updateUIViewController(_ tableViewController: UITableViewController, context: Context) {
}
class Coordinator: NSObject, UITableViewDataSource, UITableViewDelegate {
var parent: SearchableList
let tableViewController = UITableViewController()
init(_ searchableList: SearchableList) {
self.parent = searchableList
super.init()
tableViewController.tableView.dataSource = self
tableViewController.tableView.delegate = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parent.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let string = self.parent.data[indexPath.row]
let view = parent.viewBuilder(string)
let hostingController = UIHostingController(rootView: view)
let cell = SearchableListCell(withContent: hostingController, reuseIdentifier: "cell")
// Tried it with and without this line:
tableViewController.addChild(hostingController)
return cell
}
}
}
当我运行这个程序时,例如使用这个预览设置:
#if DEBUG
struct SearchableList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
SearchableList(data: ["Berlin", "Dresden", "Leipzig", "Hamburg"]) { string in
NavigationLink(destination: Text(string)) { Text(string) }
}
.navigationBarTitle("Cities")
}
}
}
#endif
我只看到一个有4个明显空白单元格的TableView。但在视图层次结构调试器中,我可以看到每个单元格确实都有导航链接和文本作为子视图,只是不可见。因此,我认为这与将UIHostingController添加为UITableViewController的子项有关,但我不知道应该在哪里添加它。
现在有办法解决这个问题吗?
UITableView
在UITableViewRepresentable
内部工作,因为需要一个UINavigationController
子类。如果您在SwiftUI应用程序中的UIKit表格中使用SwiftUI唯一可以获得的好处是...向前兼容性?PreviewProvider?那么,请记住,UIViewControllerRepresentable
被认为只是SwiftUI视图。 - user7014451SwiftUI
按钮替换添加按钮.... - user7014451