我制作了一个自定义单元格类,它从 firebase 获取数据。一切正常,但发生的情况是添加新数据时,显示在底部而不是顶部。在我提到的将新项目插入到索引路径 0 的代码中。代码仍然无法正常工作
这是代码..
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
@IBOutlet weak var save: UIButton!
@IBOutlet weak var table: UITableView!
var firebase = Firebase(url: "https://meanwhile.firebaseio.com")
var messages = [String]()
var uid:String = ""
override func viewDidLoad() {
super.viewDidLoad()
var localArray = [String]()
firebase.observeEventType(.ChildAdded, withBlock: { snapshot in
//print(snapshot.value)
let msgText = snapshot.value.objectForKey("text") as! String
localArray.insert(msgText, atIndex: 0)
self.messages = localArray
self.table.reloadData()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("Vish", forIndexPath: indexPath) as! CustomTableViewCell
let fdata = self.messages[indexPath.item]
cell.data.text = fdata as? String
return cell
}
}
最佳答案
我没有看到这里的代码,但你提到你正在使用自定义表格单元格来加载数据。
如果您要在 CustomTableViewCell
类中加载数据,您要么必须非常小心操作方式,要么将单元格的数据加载移到别处。
这是因为 dequeueReusableCellWithIdentifier
。 UITableView
不会为表格的每一行创建一个 UITableViewCell
,而是维护一个较小的单元格队列,它可以重复使用这些单元格以减少内存使用并提高性能。
The returned UITableViewCell object is frequently one that the application reuses for performance reasons.
检查您是否正在共享状态(您没有预料到)和/或在您的 CustomTableViewCell
中存在竞争条件。
这些错误通常表现为 TableView 数据出现在错误的单元格中。
关于ios - 使用 Swift 从 firebase 获取自定义单元类中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703128/