我有一个api调用,在那里我将获取所有名称,并且我将附加到一个var以显示在我的集合视图标签中。但是值不会附加到我的var。
这里代码:
var mobkam = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.getallLoans()
}
func getallLoans(){
Manager.sharedInstance.getallLoans { (data, err) in
if let _ = err{
}else{
if let dataa = data as? String{
if let dataFromString = dataa.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
print(json) // correctly display all names like ["1","2", etc]
self.mobileOprator.removeAll()
for (_, val) in json {
print(val.rawString()) // displaying the correct each items names
self.mobkam.append(val.rawString()!)
}
}
}
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.mobkam.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! NameCollectionViewCell
cell.NameLabel.text = self.mobkam[indexPath.item]
return cell
}
我做错了什么?无法解决。我错过了任何一个。请帮帮我。
谢谢!
答案 0 :(得分:1)
加载collectionView.reloadData()
中的所有值后,您只需致电getallLoans
。
当您进行API调用时,这是一个异步任务,需要一些时间才能完成。您的集合视图已经加载了它的数据源,因此您需要通知它数据已更改。然后,它将再次调用CollectionViewDataSource委托方法,并根据更新的数据刷新视图。
for (_, val) in json {
print(val.rawString()) // displaying the correct each items names
self.mobkam.append(val.rawString()!)
}
collectionView.reloadData()