Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - CollectionView not display data after parsing JSON

After parsing JSON I got my data in arraOfData of ViewController, but collectionView not display this. If I use static array all working. collectionview.reloadData() is not working. In my opinion, need somehow waiting data from parsing, then try load collectionView. I tried use refresherControler for waiting data, but I don't know where put method "endRefreshing" (i guess startRefreshing need in ViewDidLoad) If I use reloadData like didSet in arraOfData I got error cause collectionView is nil. Use reloadData right after got data from parsing same didn't work for me And a big request to tell a couple of resources (articles) on this topic, I feel that I have big problems with displaying data and in what sequence functions start to load. Thanks a lot.

class ViewController: UIViewController {


@IBOutlet weak var collectionView: UICollectionView!


var arraOfData = [GettingMoney]() {
    didSet {
        print("Changes: (arraOfData.count)")
    }
}

//  let arr = ["1", "2", "3"] - test, if i use this array, collectionView display data

  override func viewDidLoad() {
    super.viewDidLoad()
    GettingMoney.fetchData()

    collectionView.dataSource = self
    collectionView.delegate = self

  }

}

extension ViewController: UICollectionViewDelegate, 
   UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return arraOfData.count
}

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as? CollectionViewCell
    cell?.currentCurrency.text = "(arraOfData[indexPath.row])"
    return cell!

  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As this

GettingMoney.fetchData()

is a sign of asynchronous process that doesn't reload the collection , so do

func fetchData(completion:@escaping ([String]) -> ()) {
    Api.load {
      completion(arr)
    }
} 

Then use like

GettingMoney.fetchData { arr in
   self.arraOfData = arr
   DispatchQueue.main.async {
     self.collectionView.reloadData()
  }
}

A not direct case like yours is here Returning data from async call in Swift function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...