2017-05-04 69 views
0

我有抓住JSON和追加從JSON單個值到數組像這樣的方法:的UITableView不被填充

internal let methods = Methods() 
var countryData = [""] 
@IBOutlet weak var countryTableView: UITableView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    displayCountries() 
} 

func displayCountries() { 

    // Wait for task to complete before grabbing JSON 
    methods.getCountriesData {() ->() in 

     for (_, value) in self.methods.getJSON() { 
      self.countryData.append(String(describing: value)) 
     } 

     DispatchQueue.main.async { 
      self.countryTableView.reloadData() 
      print(self.countryData) 
     } 

    } 

} 

我的UITableView代表聲明,像這樣也:

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

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell 

    let row = indexPath.row 
    cell.textLabel?.text = self.countryData[row] 

    return cell 
} 

print(self.countryData)打印日誌中的所有國家(100個國家),但由於某些原因,這些國家沒有顯示在UITableView中,有誰知道爲什麼?

+0

有指定的表視圖的'dataSource'?表視圖的幀不是0x0? – nathan

+0

我還沒有指定dataSource。 TableView的框架在視圖中可見,但沒有單元格 – KTOV

+0

只有在指定表視圖的數據源時纔會調用這些'tableView'方法。這可以在代碼或故事板中完成。 – nathan

回答

0

您需要指定表視圖的數據源。這可以在代碼或故事板中完成。

在代碼:

countryTableView.dataSource = self 

您還需要將您的數據源對象符合UITableViewDataSource協議:

MyViewController: UIViewController, UITableViewDataSource { 

由於數據是字符串和屬性的數組在視圖控制器上,這應該工作正常。

在情節串連圖板:

只需將dataSource出口拖動到其被提供數據的對象(在此實例中它是視圖控制器):

screenshot of the data source outlet connection

+0

謝謝,出於某種原因在這一行let cell = tableView.dequeueReusableCell(withIdentifier:「Cell」)!作爲UITableViewCell它打破了,因爲它表明它已經發現零,同時展開一個可選值? – KTOV

+0

您是否在故事板中將單元格的標識符設置爲「單元格」? – nathan

+0

我在viewLoad階段沒有任何單元,因爲它們是以編程方式添加的,應該做什麼? – KTOV