ios - 使用 Swift 从 firebase 获取自定义单元类中的数据

标签 ios swift uitableview firebase

我制作了一个自定义单元格类,它从 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 类中加载数据,您要么必须非常小心操作方式,要么将单元格的数据加载移到别处。

这是因为 dequeueReusableCellWithIdentifierUITableView 不会为表格的每一行创建一个 UITableViewCell,而是维护一个较小的单元格队列,它可以重复使用这些单元格以减少内存使用并提高性能。

The returned UITableViewCell object is frequently one that the application reuses for performance reasons.

检查您是否正在共享状态(您没有预料到)和/或在您的 CustomTableViewCell 中存在竞争条件。

这些错误通常表现为 TableView 数据出现在错误的单元格中。

来源:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/index.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView:cellForRowAtIndexPath :

关于ios - 使用 Swift 从 firebase 获取自定义单元类中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703128/

相关文章:

ios - 在我的 Apple Developer 订阅到期后,我的 Apple Wallet Pass 生成器还能工作吗?

ios - 如何实现tableview底部的Refresh控件?

swift - UITableViewCell 可选图像

ios - 在 Realm 中编辑属性后删除对象引发 RLMException 原因 : 'Index 0 is out of bounds (must be less than 0)'

ios - 从使用 Mirror 创建的字典中过滤 nil 值

ios - 在文本字段内点击时如何添加 UIPickerView?

ios - 为搜索栏委托(delegate)赋值 - Swift

ios - 如何在顺序命令之间传递数据?

ios - 取消选择行的适当位置

ios - 如何在ios swift中实时更新单元格内容时实时更新tableview单元格内容