2017-05-04 137 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