【问题标题】:Firebase database not pulling data to custom cell in tableviewFirebase 数据库未将数据拉到 tableview 中的自定义单元格
【发布时间】:2018-03-19 15:41:05
【问题描述】:

自定义单元格不出现且不显示来自 firebase 数据库的数据时遇到问题 - 不确定哪个是问题所在,但我在 tableview 中只得到一堆非自定义单元格,而不是标题和描述。

我试图查看数据打印出来但什么也没有出现,我的代码有问题吗?调试器没有显示任何特殊内容。

import UIKit
import FirebaseDatabase

class SearchViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var tableView: UITableView!

    //part of load posts
    var posts = [Post]()
    func loadPosts(){
        var posts = [Post]()
        Database.database().reference().child("Posts").observe(.childAdded) {(snapshot: DataSnapshot) in
            if let dict = snapshot.value as? [String: Any] {
                let captionText = dict["caption"] as! String
                let descriptionText = dict["description"] as! String
                let photoUrlString = dict["photoUrl"] as! String
                let tagsText = dict["tags"] as! String
                let post = Post(captionText: captionText, descriptionText: descriptionText, photoUrlString: photoUrlString, tagsText: tagsText)
                posts.append(post)
                print(self.posts)
                self.tableView.reloadData()
            }
        }
    }

    //part of SearchBar
    let searchBar = UISearchBar()

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.endEditing(true)
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.endEditing(true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        createSearchBar()
        tableView.dataSource = self
        tableView.delegate = self
        loadPosts()
    }
    func createSearchBar(){        
        searchBar.showsCancelButton = false
        searchBar.placeholder = "Enter Here"
        searchBar.delegate = self

        self.navigationItem.titleView = searchBar
    }
}

//part of tableView
extension SearchViewController: UITableViewDataSource, UITableViewDelegate {    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return posts.count
    }    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier:"searchCell", for: indexPath)
        as! CustomTableViewCell
        cell.titleField?.text = posts[indexPath.row].caption
        //cell.descriptionField?.text = posts.description
        cell.tagsField?.text = posts[indexPath.row].tags
        return cell
    }
}

【问题讨论】:

    标签: uitableview firebase firebase-realtime-database tableview custom-cell


    【解决方案1】:

    您有两个名为“posts”的数据数组。外部的对象范围一永远不会被设置。去掉里面的。

    【讨论】:

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