Classes: ViewControllerTableViewCell and主页///这个单元格类用于主页上的单元格
问题:一个按钮按触发1)一个IBAction更新了firebase数据库(在ViewControllerTableViewCell)和2)一个模型(在ViewControllerTableViewCell和主页),使UI通过table.reloadData改变。
问题是reloadData导致错误的行被识别并在firebase中为错误的行更新。我通过删除reloadData来检查这一点,然后通过IBAction在firebase中更新正确的行。据推测,这是因为reloadData在数据库完成之前执行,然后它返回的行是错误的。我只在Xcode 13中遇到这个问题。
类ViewControllerTableViewCell:
@IBAction func buttonPressed(_ sender: UIButton) {
...
**ref.child("users").child(self.postID).updateChildValues(updates)**
}
@objc func likeButtonTapped() {
// Calls the corresponding function of the delegate, which is set to the view controller.
delegate?.didTapLikeButton(on: row, didLike: !model.didLike)
}
override func awakeFromNib() {
like?.addTarget(self, action: #selector(likeButtonTapped), for: .touchUpInside)
}
func setup(with model: CellModel) {
}
类主页
//in cellforRowAt {
cell.setup(with: model)
}
// in viewdidLoad {
setupmodels()
}
private func setupModels() {
....
models.append(model)
}
extension homepage: ViewControllerTableViewCellDelegate {
// Called from the cell's button action through the delegate property.
func didTapLikeButton(on row: Int, didLike: Bool) {
// Updates the corresponding cell's model so that it will update the cell when
// the table view reloads with the updated models.
models[row].didLike = didLike
**table.reloadData**
print("BBBBBBBBB")
}
//在第一个答案后添加
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ViewControllerTableViewCell {
let immy = cell.viewWithTag(1) as? UIImageView
let like = cell.viewWithTag(3) as? UIButton
let person: Userx = people[indexPath.row]
let text = person.Education
cell.lblName.text = person.Education
cell.lblName.text = text?.uppercased()
let person5 = colorArray[indexPath.row]
let person6 = colorArray1[indexPath.row]
let person7 = colorArray2[indexPath.row]
cell.lblName?.layer.masksToBounds = true
cell.lblName?.backgroundColor = person5
like?.backgroundColor = person6
immy?.backgroundColor = person7
cell.lblName.baselineAdjustment = .alignCenters
cell.postID = self.people[indexPath.row].postID
if let PhotoPosts = person.PhotoPosts {
let url = URL(string: PhotoPosts)
print(PhotoPosts, "sttdb")
immy?.sd_setImage(with: url)
}
cell.row = indexPath.row
// Assigns the delegate property to this view controller.
cell.delegate = self
cell.delegate2 = self
let model = models[indexPath.row]
let modell = modelss[indexPath.row]
like?.isUserInteractionEnabled = true
cell.setup(with: model)
cell.setup1(with: modell)
return cell
}
return UITableViewCell()
}
如注释所示,
-
在
didTapLikeButton
上,更新更改到当前模型。 -
tableView.reloadData()
,而是重新加载tableView row
tableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: .automatic)
我认为你在tableView中只有1个section,如果没有,那么得到section或indexPath
并在上面的代码中传递它。