Как получить значение из Firestore, чтобы изменить текст кнопки в ячейке таблицы для каждого элемента прослушивания? - PullRequest
1 голос
/ 17 октября 2019

У меня есть табличное представление, в котором есть элемент списка, и каждая ячейка имеет кнопку, я хочу исправить текст и цвет кнопки на основе логического значения, полученного из магазина, кнопка каждой ячейки имеет определенный текст и цвет, основанный на этомтолько значение, я знаю синтаксис для установки текста и цвета для кнопки в swift, я просто не могу сделать это на основе значения из пожарного магазина, ниже приведен код

код для получениясписок, соответствующим значением является checkl1value

func getComments() {

      //print(postId + "received")
        let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")

        commentsRef.getDocuments { (snapshot, error) in

            if let error = error {

                print(error.localizedDescription)

            } else {

                if let snapshot = snapshot {

                    for document in snapshot.documents {


                        let data = document.data()
                        let username = data["comment_author_username"] as? String ?? ""
                        let comment = data["comment_author_comment"] as? String ?? ""
                        let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
                        let fullname = data["comment_author_fullname"] as? String ?? ""
                        let email = data["comment_author_email"] as? String ?? ""
                        let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
                        let commentuser_id = data["comment_author_id"] as? String ??  ""
                        self.checkl1value  = data["l1"] as? DarwinBoolean


                        let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
                        self.comments.append(newComment)

                    }
                    self.tableView.reloadData()
                }
            }
        }
    }

Код для cellForRowAt

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


        cell.commentLikebutton.tag = indexPath.row
        cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)


        if checkl1value == true {
        cell.commentLikebutton.setTitle("Text1", for: .normal)
        //  cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
            cell.commentLikebutton.backgroundColor = UIColor.red
            //cell.commentLikebutton.backgroundColor = UIColor?.red()
        }
        else{
            cell.commentLikebutton.setTitle("Text2", for: .normal)

        }


            cell.set(comment: comments[indexPath.row])

        return cell


    }

Ответы [ 2 ]

1 голос
/ 17 октября 2019

Добавьте что-то вроде этого на вершину cellForRowAt

let thisComment = self.comments[indexPath.row]
let checkl1value = thisComment.checkl1value

0 голосов
/ 17 октября 2019

Я думаю, что ошибка в том, что ваше checkl1Value всегда изменяется со значением последнего элемента в массиве. Вы можете сделать что-то вроде этого:

var booleanValues = [DarwinBoolean]()
func getComments() {
  let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")

  commentsRef.getDocuments { (snapshot, error) in

    if let error = error {
      print(error.localizedDescription)
    } else {
      if let snapshot = snapshot {
        for document in snapshot.documents {

          let data = document.data()
          let username = data["comment_author_username"] as? String ?? ""
          let comment = data["comment_author_comment"] as? String ?? ""
          let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
          let fullname = data["comment_author_fullname"] as? String ?? ""
          let email = data["comment_author_email"] as? String ?? ""
          let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
          let commentuser_id = data["comment_author_id"] as? String ??  ""
          // self.checkl1value  = data["l1"] as? DarwinBoolean
          booleanValues.append(data["l1"] as? DarwinBoolean ?? false)

          let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
          self.comments.append(newComment)
        }
        self.tableView.reloadData()
      }
    }
  }
}

CellForRowAt:

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

  cell.commentLikebutton.tag = indexPath.row
  cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)


  if booleanValues[indexPath.row] {
    cell.commentLikebutton.setTitle("Text1", for: .normal)
    //  cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
    cell.commentLikebutton.backgroundColor = UIColor.red
    //cell.commentLikebutton.backgroundColor = UIColor?.red()
  } else {
    cell.commentLikebutton.setTitle("Text2", for: .normal)
  }

  cell.set(comment: comments[indexPath.row])

  return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...