I am facing this weird problem of updating a button in a cell on click. I have this like button which i change depend on status i get in response when i click the button. So when the like status is false. I show it in grey and on click if the status in back-end changes and if i get the status as true in response i change it to pink and vice- versa. The issue is for the first time. once i change the cell the functionality works as expected.
Here is my code
I made a variable for the cell to access it globally
var TheVideoPlayerCell:VideoPlayerCell?
func registerTableCells(){
myTable.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell")
myTable.register(UINib(nibName: "VideoPlayerCell", bundle: nil), forCellReuseIdentifier: "VideoPlayerCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoArrObj?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoPlayerCell", for: indexPath) as! VideoPlayerCell
TheVideoPlayerCell = cell
cell.obj = videoArrObj?[indexPath.row]
cell.btn_Likes.addTarget(self, action: #selector(onClickLike), for: .touchUpInside)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(self.myTable.frame.height)
}
Once i get a response from backend
self.TheVideoPlayerCell?.btn_Likes.isEnabled = true
let obj = try JSONDecoder().decode(LikeStatusModal.self, from: data)
let likeStatus = obj.data?.like_status ?? false
let totalLikes = obj.data?.total_likes ?? ""
if likeStatus{
self.TheVideoPlayerCell?.btn_Likes.setImage(UIImage(named: "icon_like_selected"), for: .normal)
}else{
self.TheVideoPlayerCell?.btn_Likes.setImage(UIImage(named: "icon_like_unselected"), for: .normal)
}
if totalLikes != ""{
self.TheVideoPlayerCell?.lbl_NoOfLikes.text = totalLikes
}
self.TheVideoPlayerCell?.obj?.is_like = likeStatus
self.TheVideoPlayerCell?.obj?.likes = totalLikes
self.videoArrObj?[self.currentIndex].is_like = likeStatus
self.videoArrObj?[self.currentIndex].likes = totalLikes