2016-11-23 2 views
0

Я очень начинаю Swift - заполняю табличный вид из данных Firebase.Swift - когда данные фактически загружены в TableViewController

В нижнем колонтитуле таблицы я хочу отобразить некоторые подсчитанные суммы под столбцами таблицы. Однако при вызове footerCell.configure(priceLines, isPortrait: isPortrait) словарь priceLines по-прежнему пуст.

Как исправить это?

Спасибо заранее, Андре Хартмана, Бельгия

import UIKit 
import FirebaseDatabase 

class ListTableViewController: UITableViewController { 
    var priceLines = [NSDictionary]() 
    var isPortrait = false 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ListTableViewController.rotated), name: UIDeviceOrientationDidChangeNotification, object: nil) 
     loadDataFromFirebase() 
    } 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return priceLines.count 
    } 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("profileCell", forIndexPath: indexPath) as! PriceTableViewCell 
     cell.configure(priceLines, row: indexPath.row, isPortrait: isPortrait, source: "intraday") 
     return cell 
    } 
    override func tableView(tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? { 
     let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell 
     headerCell.configure(isPortrait) 
     return headerCell 
    } 
    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { 
     let footerCell = tableView.dequeueReusableCellWithIdentifier("FooterCell") as! CustomFooterCell 
     footerCell.configure(priceLines, isPortrait: isPortrait) 
     return footerCell 
    } 
    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 
     return 30.0 
    } 
    override func tableView (tableView:UITableView, heightForHeaderInSection section:Int) -> CGFloat 
    { 
     return 50.0; 
    } 

    // MARK:- Load data from Firebase 
    func loadDataFromFirebase() { 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
     refInter.observeEventType(.Value, withBlock: { snapshot in 
      var tempItems = [NSDictionary]() 
      for item in snapshot.children { 
       let child = item as! FIRDataSnapshot 
       let dict = child.value as! NSDictionary 
       tempItems.append(dict) 
      } 
      self.priceLines = tempItems 
      self.tableView.reloadData() 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
     }) 
    } 
    func rotated() 
    { 
     let newDisplay = (UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) 
     if(newDisplay != isPortrait){ 
      self.tableView.reloadData() 
     } 
     isPortrait = newDisplay 
    } 
} 
+0

Данные обновляются, когда вы вызываете 'reloadData() ', но если вы поворачиваете экран перед загрузкой данных в первый раз, ничего не произойдет, потому что извлечение Firebase работает асинхронно. – vadian

ответ

0

Документация clearly says что

Когда табличное собирается появиться в первый раз он загружен, стол с видом на контроллер перезагружается данные табличного представления.

Таким образом, он автоматически перезагрузит таблицу где-то между viewDidLoad и viewWillAppear. Ваш priceLines пуст в этой точке и будет заполнен данными только в том случае, если закрыт метод loadDataFromFirebase. Я не уверен, когда это произойдет в вашем случае, но, когда вы вызываете неявно reloadData, вы должны иметь уже priceLines непусто (конечно, если результаты в закрытии имеют некоторые данные)

Смежные вопросы