【发布时间】:2021-12-09 21:18:23
【问题描述】:
我有一个 UITableView,它可以从 Firebase 实时数据库中提取一些信息。所有信息都被正确地提取和填充,并在应该删除时删除,但我遇到了一个奇怪的错误。如果表格视图中有多个单元格,当我删除其中一个单元格时,该单元格不会消失,它只会被剩余单元格之一的副本替换。然后当我关闭表格视图并重新打开它时,一切都是正确的(即复制的单元格消失了)。我在下面附上了一些照片作为说明。这是表格视图的 swift 文件:
import UIKit
import Firebase
import FirebaseAuth
class SpotRemove: ViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tblSpots: UITableView!
var spotsList = [ArtistModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return spotsList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
let spot: ArtistModel
spot = spotsList[indexPath.row]
cell.lblName.text = spot.type
cell.lblGenre.text = spot.avail
cell.lblPrice.text = spot.price
return cell
}
var refSpots: DatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
tblSpots.allowsMultipleSelectionDuringEditing = true
refSpots = Database.database().reference().child("Spots")
refSpots?.observe(.value, with: { (snapshot) in
if snapshot.childrenCount>0{
for spots in snapshot.children.allObjects as![DataSnapshot]{
let spotKey = spots.key
let spotObject = spots.value as? [String: AnyObject]
let spotType = spotObject?["Type"]
let spotAvail = spotObject?["Availability"]
let spotPrice = spotObject?["Price"]
let spotID = spotObject?["UserID"]
let spot = ArtistModel(id: spotID as! String?, avail: spotAvail as! String?, type: spotType as! String?, price: spotPrice as! String?, key: spotKey as! String?)
let userID = Auth.auth().currentUser?.uid
if userID == spotID as? String {
self.spotsList.append(spot)
}
}
self.tblSpots.reloadData()
}
})
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let spot = self.spotsList[indexPath.row]
if let spotKey = spot.key {
Database.database().reference().child("Spots").child(spotKey).removeValue { (error, ref) in
if error != nil {
print("Failed to delete message:", error!)
return
}
self.spotsList.remove(at: indexPath.row)
self.tblSpots.deleteRows(at: [indexPath], with: .automatic)
self.tblSpots.reloadData()
}
tblSpots.reloadData()
}
}
}
我认为问题在于我在没有更改 numberOfRowsInSection 的情况下调用 reloadData()。修复是否像在我调用重新加载数据之前放置 numberOfRowsInSection = numberOfRowsInSection - 1 这样的简单?提前谢谢大家。
The reloaded table view showing only the remaining cell (as it is supposed to)
【问题讨论】:
-
从不在
deleteRows之后立即调用reloadData。删除该行。insert/delete/moveRows确实更新了 UI。并删除方法中第二次出现的reloadData。它没有效果。 -
那么,如果我删除这两个 reloadData 实例,它应该可以工作吗?还是我还应该输入 numberOfRowsInSection - 1 之类的内容?
-
不,只需删除两个出现的
reloadData()。 -
谢谢,我现在就试试。
-
我已经删除了这两个 reloadData() 实例,但这并没有改变用户端的任何内容。
标签: ios swift xcode uitableview