Tableview in UITableviewcell

Jerry PM
2 min readDec 13, 2021

--

If you want to create dynamic table view

Source: Author

Have you ever tried to include TableView in UITableViewCell but failed, this time I’ll give an example of one way to create dynamic size for tableview in UITableViewCell

# Use this custom TableView size

Step one create table view and custom table view cell, in that cell there is another table view, the following is how to make the table in the cell auto height. add the following custom table into the custom class.

This table view custom function to set size to auto height for table inside cell tableview

For second cell I give name SecondTableViewCell, when you have dynamic data you can use this “.layoutIfneeded()”

import UIKitclass FirstTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
setupTableView()
} private func setupTableView() {
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.register(UINib(nibName: "SecondTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
tableView.separatorColor = .darkGray
tableView.separatorInset = UIEdgeInsets.zero
}
func reloadData() {
DispatchQueue.main.async {
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
}
}
}extension FirstTableViewCell: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SecondTableViewCell
cell.titleLabel.text = "Sub Table Cell \(indexPath.row)"
cell.backgroundColor = .blue.withAlphaComponent(0.5)
return cell
}
}

--

--