I have situation where I have to use UIKit
custom view with TableView
inside SwiftUI
but table view is not appearing in SwiftUI
, however delegate methods are executing except for the cellForRow
. I am not using storyboard in my project.
Example
Here is my custom view with my tableview and delegate methods
class CustomTableView: UIView, UITableViewDelegate, UITableViewDataSource {
var tableView: MyCustomTableView {
let tableview = MyCustomTableView(frame: .zero, style: .plain)
tableview.delegate = self
tableview.dataSource = self
return tableview
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Hello (indexPath.row)"
return cell
}
}
This is my tableview
class MyCustomTableView: UITableView {
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
This is my Representable for CustomTableView
struct CustomTableViewRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> CustomTableView {
CustomTableView(frame: .zero)
}
func updateUIView(_ uiView: CustomTableView, context: Context) {
uiView.tableView.reloadData()
}
}
This is my SwiftUI view which will load on one of the button click event
struct SwiftUIView: View {
var body: some View {
VStack {
CustomTableViewRepresentable()
}.background(Color.yellow)
}
}
Please help and advise. Thanks.
I added code in details section that I tried but I have no luck. I am missing something but don’t know what is it?
Here is the link to Sample project: https://www.dropbox.com/s/q0nfphass8tohhb/TableViewPOC.zip?dl=0
2
Answers
You have neither set your
MyCustomTableView
‘s frame nor setAutolayout
constrains.Please give enough layout data to it so that it can be successfully rendered.
You need to register a
Cell
, so you need to callregister(_:forReuseIdentifier:)
, as follows:So use one of the following:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell")
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "DefaultCell")
tableView.register(UINib(nibName: "yourNib", bundle: nil), forCellReuseIdentifier: "DefaultCell")
And later in
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
, you’ll need to manipulate the registered cell by usingdequeueReusableCell(withIdentifier:)
, like the following: