I have two view controllers which have same tableview. One is for Post and one is for Profile, which also contains a post by a user. I have decided to reuse the code, so I have created the class PostTableView
.
class PostTableView: UITableView {
var arrayPosts:[PostTableViewCompitible] = [] {
didSet {
self.reloadData()
}
}
var btnCommentTapped:((ArrayInspireListCell) -> ())?
var heightOfRows = Dictionary<IndexPath, CGFloat>()
var indexOfCellBeforeDragging = 0
override func awakeFromNib() {
super.awakeFromNib()
setupTableView()
}
private func setupTableView() {
self.register(UINib.init(nibName: StoryBoard.Cells.ArrayInspireListCell, bundle: nil), forCellReuseIdentifier: StoryBoard.Cells.ArrayInspireListCell)
self.dataSource = self
self.delegate = self
self.estimatedRowHeight = 470
// self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.rowHeight = UITableViewAutomaticDimension
self.separatorStyle = .none
}
}
With Delegate / Data source:
extension PostTableView:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayPosts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = self.arrayPosts[indexPath.row]
let cell = post.cellForTableView(tableview: tableView, atIndexPath: indexPath)
cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
cell.btnCommentTapped = self.btnCommentTapped
cell.layoutIfNeeded()
return cell
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.heightOfRows[indexPath] {
return height
}
return 470
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let height = cell.frame.size.height
self.heightOfRows[indexPath] = height + 30
}
}
Is it good practice to do so?