加载自定义函数后如何初始化collectionView

How to init collectionView after loading custom function

我在 class MoviesViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UIScrollViewDelegate {

里面的 func collectionView 有问题

这个函数是自动启动的,我不想自动启动。或者在完成加载外部数据的函数时执行此操作。

这是我的ViewController.swift

的结构代码
class MyViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UIScrollViewDelegate {
  @IBOutlet var scrollView : UIScrollView!
  @IBOutlet var collectionView1 : UICollectionView!

这是我要在 CollectionView

之前加载的函数
func loaddata(){
  let url: NSURL = NSURL(string: "http://www.mywebsite/testdata.php")!
  let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
  let bodyData = "data=something"
  request.HTTPMethod = "POST"

  request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
  NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
  (response, data, error) in
    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!               
  }
}

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

override func viewDidLayoutSubviews() {
  self.scrollView!.contentSize = CGSizeMake(1920, 2200)
}

在这里,func CollectionView 自动初始化

//this is function that load automatically
func collectionView(collectionView: UICollectionView,
  layout collectionViewLayout: UICollectionViewLayout,
  insetForSectionAtIndex section: Int) -> UIEdgeInsets {
  return UIEdgeInsets(top: 0.0, left: 50.0, bottom: 0.0, right: 50.0)
}

// this is function load automatically
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  if (collectionView == self.collectionView1) {
    let cell : FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! FeaturedCollectionViewCell
    let  imageFilename = "featured-\(indexPath.row).jpg"
    cell.featuredImage.image = UIImage(named: imageFilename)
    return cell
  }
  return UICollectionViewCell()
}

我怎样才能让 ViewControllerloadData 之前开始?或者 ViewController 在您从 loadData

调用函数之前不启动

当您还没有项目时,您不应该关心集合视图加载项目。可能发生的最坏情况是什么都不显示。

但是,当您的数据加载完成后,您应该调用 collectionView.reloadData 来显示您刚从服务器加载完成的数据。

如果您不想在数据仍在加载时显示集合视图,只需在完成处理程序中设置 collectionView.hidden = true 然后 collectionView.hidden = false。您可能还应该显示一个 activity 指示符(例如 UIActivityIndicator 实例)以通知用户数据仍在加载中。

另外,我建议不要从 viewDidLoad 加载数据。您应该使用 viewDidAppear.