Обновите кнопку в ячейке, используемой в табличном представлении, в зависимости от статуса, не перезагружая ячейку - PullRequest
0 голосов
/ 11 января 2020

Я столкнулся с этой странной проблемой обновления кнопки в ячейке при нажатии. У меня есть кнопка «Мне нравится», которую я меняю в зависимости от статуса, который я получаю в ответ, когда нажимаю кнопку. Таким образом, когда подобное состояние ложно. Я показываю его серым цветом и по щелчку, если изменяется статус на внутреннем сервере, и если я получаю статус как истинный в ответ, я меняю его на розовый и наоборот. Вопрос в первый раз. как только я изменяю ячейку, функциональность работает как положено.

Вот мой код

Я сделал переменную для ячейки, чтобы получить к ней глобальный доступ

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)
}

Как только я получаю ответ от бэкэнда

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

enter image description here

1 Ответ

0 голосов
/ 11 января 2020

Вы получаете неправильный указатель. Попробуйте получить доступ к ячейке таким образом.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "VideoPlayerCell", for: indexPath) as! VideoPlayerCell

    cell.obj = videoArrObj?[indexPath.row]
    cell.btn_likes.tag = indexPath.row
    cell.btn_Likes.addTarget(self, action: #selector(onClickLike(sender:)), for: .touchUpInside)
    cell.selectionStyle = .none
    return cell
}


func onClickLike(sender : UIButton) {
    // Here is have the api request for that video obj
    ServiceSuccessData(action : "YourString", data : Data, index : sender.tag)
}
//Once I get response from server
func ServiceSuccessData(action:String, data:Data, index : Int){
    let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) as! YourCell
    cell.btn_Likes.isEnabled = true

    DispatchQueue.main.async {
        let obj = try JSONDecoder().decode(LikeStatusModal.self, from: data)
    let likeStatus = obj.data?.like_status ??  false
    let totalLikes = obj.data?.total_likes ?? ""
    if likeStatus{
        cell.btn_Likes.setImage(UIImage(named: "icon_like_selected"), for: .normal)
     } else {
        cell.btn_Likes.setImage(UIImage(named: "icon_like_unselected"), for: .normal)
     }
     if totalLikes != ""{
          cell.lbl_NoOfLikes.text = totalLikes
     }
     cell.obj?.is_like = likeStatus
     cell.obj?.likes = totalLikes
     self.videoArrObj?[self.currentIndex].is_like = likeStatus
     self.videoArrObj?[self.currentIndex].likes = totalLikes
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...