简体   繁体   中英

empty tableview cell for at index path row is not called

All the tableview functions are working except cell for row index path .

The problem maybe that foods array is empty so the number for rows is 0 so the cell for row at index path is not called

@IBOutlet weak var foooods: UITableView!
var databaseref = Database.database().reference()
var img : AnyObject?
var foods = [String?]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.databaseref.child("basic food").observe(.childAdded, with: {( snap: DataSnapshot) in
        let snapp = snap.value as! [String:AnyObject]
        if let x = snapp["name"] as! String? {
            self.foods.insert(x, at: 0)
            //self.foods.append(x)
        }
    })
    self.foooods.reloadData()
}

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.foods.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    print("difufuehf")
    let cell : foodsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "aupa", for:indexPath) as! foodsTableViewCell
    print("fufvksdfvysdgfvjdsgfdsygfvds,jhvjsdvsdjvguydsfgdsylfgdsyfgsdlygfsiygf")
    if let foo =  foods[indexPath.row]  {
        print(foo)
        cell.food.text = foo
    }
    return cell
}

This must be a duplicate but I can't find one.

Your issue is that you call reloadData in the wrong place which results in it being called far too soon. You need to call it inside the completion block, after you update your data model.

And you need to make sure it gets called on the main queue.

override func viewDidLoad() {
    super.viewDidLoad()

    self.databaseref.child("basic food").observe(.childAdded, with: {( snap: DataSnapshot) in
        if let snapp = snap.value as? [String:Any], let x = snapp["name"] as? String {
            self.foods.insert(x, at: 0)
            //self.foods.append(x)

            DispatchQueue.main.async {
                self.foooods.reloadData()
            }
        }
    })
}

Note that I also fixed the way the value is obtained. You really need to avoid force unwrapping and force casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM