El estado del botón se activa en celdas incorrectas
Agregué un botón a las celdas y agregué acción, por lo que si el usuario lo toca, el estado es "No me gusta" y si el usuario toca nuevamente, el estado es "Me gusta". Sin embargo, el estado también se aplica a otros botones de celda. Y si me desplazo rápido, solo selecciona aleatoriamente qué botón de celda debe tener el estado. ¿Qué causa esto?
Llamo botón con función dentrocellForRowAt indexPath: IndexPath
funciona así:
cell.likeButton.addTarget(self, action: #selector(like), for: .touchUpInside)
Y esta es la función asignada al botón:
func like(sender: UIButton){
let section = 0
let row = sender.tag
let indexPath = IndexPath(row: row, section: section)
let cell: FeedTableViewCell = tableView.dequeueReusableCell(withIdentifier: "feedCell", for: indexPath) as! FeedTableViewCell
FIRDatabase.database().reference().child("posts").child(postsArray[indexPath.row].key).runTransactionBlock({ (currentData: FIRMutableData) -> FIRTransactionResult in
if var post = currentData.value as? [String : AnyObject], let uid = FIRAuth.auth()?.currentUser?.uid {
var stars : Dictionary<String, Bool>
stars = post["stars"] as? [String : Bool] ?? [:]
var starCount = post["starCount"] as? Int ?? 0
if let _ = stars[uid] {
// Unstar the post and remove self from stars
starCount -= 1
stars.removeValue(forKey: uid)
cell.likeButton.tag = indexPath.row
cell.likeButton.setTitle("Like", for: .normal)
cell.likeLabel.text = "\(starCount)"
} else {
// Star the post and add self to stars
starCount += 1
stars[uid] = true
cell.likeButton.tag = indexPath.row
cell.likeButton.setTitle("Dislike", for: .normal)
cell.likeLabel.text = "\(starCount)"
}
post["starCount"] = starCount as AnyObject?
post["stars"] = stars as AnyObject?
// Set value and report transaction success
currentData.value = post
return FIRTransactionResult.success(withValue: currentData)
}
return FIRTransactionResult.success(withValue: currentData)
}) { (error, committed, snapshot) in
if let error = error {
print(error.localizedDescription)
}
}
}
Y así creé la vista de tabla con celdas:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: FeedTableViewCell = tableView.dequeueReusableCell(withIdentifier: "feedCell", for: indexPath) as! FeedTableViewCell
cell.likeButton.tag = indexPath.row
cell.likeButton.addTarget(self, action: #selector(self.tapped), for: .touchUpInside)
}
¿Qué hace que el estado se transfiera a los otros botones también? Incluso agregué etiquetas para que detecte el botón seleccionado. ¿Hay algo que ver con la reutilización celular?
Agrega Me gusta a Firebase a la correcta.