【问题标题】:tableView doesn't show data in swifttableView 不快速显示数据
【发布时间】:2018-05-13 20:46:48
【问题描述】:

我正在尝试在 viewController 中创建一个 tableView。我知道这很烦人,但这样桌子看起来好多了。我也在尝试将来自 Firebase 的数据合并到表格中。不幸的是,当我运行代码时,它只显示一个空白表。控制台能够打印所需的数据,但它不会显示在实际表格上。请让我知道我做错了什么。非常感谢!

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
 var user = Auth.auth().currentUser

var users = [Users]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self

    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

    tableView.reloadData()

    fetchUser()

}
func fetchUser() {
    Database.database().reference(fromURL: "https://yala-2018.firebaseio.com/").child("users").observe(.childAdded, with: { (DataSnapshot) in


        if let dictionary = DataSnapshot.value as? [String: AnyObject] {
            let user = Users()
           // user.setValuesForKeys(dictionary)

            user.name = dictionary["name"] as! String
            user.age = dictionary["age"] as! String
            user.sex = dictionary["sex"] as! String
            self.users.append(user)
            print(user.name, user.age)
            DispatchQueue.main.async(execute: {
            self.tableView.reloadData()
            })
        }


    })
}
func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return users.count
}

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCell(withIdentifier: "guide", for: indexPath)

    let user = users[indexPath.row]
    cell.textLabel?.text = user.name
    cell.detailTextLabel?.text = "Age: \(user.age) Sex: \(user.sex)"

 // Configure the cell...

 return cell
 }

func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

}

【问题讨论】:

    标签: swift firebase firebase-realtime-database tableview viewcontroller


    【解决方案1】:

    将此更改为 1,因为 0 表示即使有数据也不会显示空 tableView 的任何部分,或者将其删除,默认为 1

    func numberOfSections(in tableView: UITableView) -> Int {
    
       return 1
    }
    

    【讨论】:

    • 另一个问题,我将原型单元格设置为“字幕”。我可以让 textLabel 工作,但不能让 detailTextLabel 工作。知道为什么会这样吗?我在 IB 中将单元格样式设置为副标题。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2012-01-04
    • 1970-01-01
    • 2022-11-13
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多