【问题标题】:Issue fetching data in custom cell class from firebase using Swift使用 Swift 从 firebase 获取自定义单元类中的数据的问题
【发布时间】:2016-08-10 17:32:41
【问题描述】:

我创建了一个自定义单元类,它从 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
     }
}

【问题讨论】:

  • 是否有理由将 msg 插入 localArray,然后将该数组分配给 messages 数组?哦,还有,在你的 numberOfRowsInSection 中,返回 self.messages.count 而不是 messages.count。

标签: ios swift uitableview firebase


【解决方案1】:

我没有看到这里的代码,但你提到你正在使用自定义表格单元格来加载数据。

如果您在 CustomTableViewCell 类中加载数据,您要么必须非常小心如何执行此操作,要么将单元格的数据加载移到其他地方。

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

返回的 UITableViewCell 对象经常是应用程序出于性能原因重用的对象。

检查您是否正在共享状态(您没想到会这样)和/或在您的CustomTableViewCell 中存在竞争条件。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多