【发布时间】:2016-10-13 15:43:15
【问题描述】:
我将按钮添加到单元格中并添加了操作,因此如果用户触摸它,则状态为“不喜欢”,如果用户再次触摸,则状态为“喜欢”。但是,该状态也适用于其他单元格按钮。如果我快速滚动它只是随机选择哪个单元格按钮应该具有状态。这是什么原因造成的?
我在cellForRowAt indexPath: IndexPath函数中调用按钮,函数如下:
cell.likeButton.addTarget(self, action: #selector(like), for: .touchUpInside)
这是分配给按钮的功能:
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)
}
}
}
像这样我用单元格创建了表格视图:
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)
}
是什么导致状态也转移到其他按钮?我什至添加了标签,以便它检测到选定的按钮。与细胞重复使用有关吗?
它将对 Firebase 的喜欢添加到正确的..
【问题讨论】:
-
回答你的最后一个问题,用两个词:细胞重用。您需要向我们展示您是如何创建和返回单元格的。
-
@Cyrille 我编辑了。
-
如果您的喜欢按钮是您的单元格的直接子级,您应该尝试通过询问表格视图而不是基于标签创建新的来获取
indexPath。let cellIndexPath = tableView.indexPathForCell(sender.superview) -
好点,我今晚要试试。
-
@Crazyrems 仍然无法正常工作:(