2017-02-15 95 views
0

以下是我試圖實現的內容的高級描述; 1.獲取數據 2.保存所取得的數據在數組對象 3.更新集合視圖與數組的大小UICollectionView reloadData()不更新集合視圖中的單元格

這裏是我的代碼

class ItemcollectionViewController:UICollectionViewController, UICollectionViewDelegateFlowLayout { 

    let cellId = "CellId" 
    var categories = [Category]() 
    let viewOptionVar:ViewOptionBar = { 
     let vOV = ViewOptionBar() 
     vOV.translatesAutoresizingMaskIntoConstraints = false 
     return vOV 
    }() 

    private func fetchData() { 
     let categoryController = CategoryController() 
     categoryController.getAllCategory(username: "blah", password: "password") {(returnedCategories, error) -> Void in 
      if error != nil { 
       print(error) 
       return 
      } 
      self.categories = returnedCategories! 
      print("size of the array is \(self.categories.count)") 
      OperationQueue.main.addOperation{self.collectionView?.reloadData()} 
     } 

    } 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    fetchData() 
    collectionView?.backgroundColor = UIColor.white 
    collectionView?.register(ItemCell.self, forCellWithReuseIdentifier: cellId) 
    collectionView?.contentInset = UIEdgeInsetsMake(50, 0, self.view.frame.height, self.view.frame.width) 
    collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, self.view.frame.width) 
    } 

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    print("in the method \(self.categories.count)") 
    return self.categories.count 
    } 

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ItemCell 
    cell.category = categories[indexPath.item] 
    return cell 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    return CGSize(width: 111, height: 111) 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 
    return 0 
    } 

    private func setupViweOptionBar() { 
    view.addSubview(viewOptionVar) 
    view.addConstraintsWithFormat(format: "H:|[v0]|", views: viewOptionVar) 
    view.addConstraintsWithFormat(format: "V:|[v0(50)]", views: viewOptionVar) 
    } 
} 

在日誌中我可以看到以下語句:

在方法

陣列的大小是3

並且從我的視圖中看不到任何單元格。

有人可以告訴我我做錯了什麼嗎? 在此先感謝。

編輯1 現在我正在註冊自定義單元格後提取數據。但是,它仍然無法正常工作

更新的代碼:

class ItemcollectionViewController:UICollectionViewController, UICollectionViewDelegateFlowLayout { 

    let cellId = "CellId" 
    var categories = [Category]() 
    let viewOptionVar:ViewOptionBar = { 
     let vOV = ViewOptionBar() 
     vOV.translatesAutoresizingMaskIntoConstraints = false 
     return vOV 
    }() 

    private func fetchData() { 
     let categoryController = CategoryController() 
     categoryController.getAllCategory(username: "blah", password: "password") {(returnedCategories, error) -> Void in 
      if error != nil { 
       print(error) 
       return 
      } 
      self.categories = returnedCategories! 
      print("size of the array is \(self.categories.count)") 

     } 

    } 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    collectionView?.backgroundColor = UIColor.white 
    collectionView?.register(ItemCell.self, forCellWithReuseIdentifier: cellId) 
    collectionView?.contentInset = UIEdgeInsetsMake(50, 0, self.view.frame.height, self.view.frame.width) 
    collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, self.view.frame.width) 
    collectionView?.dataSource = self 
    collectionView?.delegate = self 
    fetchData() 
    DispatchQueue.main.async{self.collectionView?.reloadData()} 
    } 

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    print("in the method \(self.categories.count)") 
    return self.categories.count 
    } 

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ItemCell 
    cell.category = categories[indexPath.item] 
    return cell 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    return CGSize(width: 111, height: 111) 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 
    return 0 
    } 

    private func setupViweOptionBar() { 
    view.addSubview(viewOptionVar) 
    view.addConstraintsWithFormat(format: "H:|[v0]|", views: viewOptionVar) 
    view.addConstraintsWithFormat(format: "V:|[v0(50)]", views: viewOptionVar) 
    } 
} 

EDIT 2

下面的代碼是我的查詢方法

func getAllCategory(username:String, password:String, callback: @escaping ([Category]?, String?) -> Void){ 
    var categories = [Category]() 
    let fetchCategories = URL(string: userURL + "all") 
    URLSession.shared.dataTask(with: fetchCategories!, completionHandler: { (data, response, error) in 
     if let err = error { 
      print(err) 
      return 
     } 
     do { 
      let jsonCategoryObj = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [[String: AnyObject]] 
      for categoryDictionary in jsonCategoryObj { 
       let category = Category() 
       category.categoryId = categoryDictionary["categoryId"] as? String 
       category.categoryName = categoryDictionary["categoryName"] as? String 
       category.categoryDescription = categoryDictionary["categoryDescription"] as? String 
       let categoryRegisteredDateString = categoryDictionary["categoryRegisteredDate"] as? String 
       let df = DateFormatter() 
       df.dateFormat = self.shapeDateFormat 
       let categoryRegisteredDate = df.date(from: categoryRegisteredDateString!)! 
       category.categoryRegisteredDate = categoryRegisteredDate 

       categories.append(category) 

      } 
      callback(categories, nil) 
     }catch let jsonError { 
      callback(nil, String(describing: jsonError)) 
     } 

    }).resume() 
} 

FYI:我知道我m沒有使用傳遞的用戶憑據,它只是來自我的不同查詢方法的複製和粘貼錯誤

+0

你好。你是否得到了解決這個問題的方法,或者你只是按照我的方式給了uo? – nyxee

回答

1
DispatchQueue.main.async{self.collectionView?.reloadData()} 
    collectionView?.backgroundColor = UIColor.white 
    collectionView?.register(ItemCell.self, forCellWithReuseIdentifier: cellId) 

您甚至在註冊單元格之前重新加載數據。

註冊您的單元格和數據源並委託方法FIRST,並重新載入數據LAST。

編輯:

我看到您編輯您的文章。

但是,即使您已經註冊了您的手機,您也是fetchData()。因此,再次,在註冊所有單元,數據源和委託之後,再移動fetchData方法。

+0

這很有道理。但是,它甚至在我將它改爲 'collectionView?.backgroundColor = UIColor.white collectionView?.register(ItemCell.self,forCellWithReuseIdentifier:cellId) collectionView?.contentInset = UIEdgeInsetsMake(50,0,self .view.frame.height,self.view.frame.width) collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50,0,0,self.view.frame.width) fetchData() DispatchQueue.main.async {self。 collectionView?.reloadData()} –

+0

@ J.GS.Han你沒有設置collectionView.delegate = self和collectionView.datasource = self,應該在我的回答中使它更清晰,但那是你現在唯一的問題。此外,我認爲你需要在你的類中添加** UICollectionViewDataSource **和** UICollectionViewDelegate **。 – 2017-02-15 06:13:28

+0

感謝您的回覆!我試圖根據您的建議解決方案更新我的代碼,但它並沒有工作。我也嘗試將** UICollectionViewDataSource **和** UICollectionViewDelegate **添加到我的類中,但它抱怨說「ItemcollectionViewController對協議'UICollectionViewDataSource'的冗餘一致性'' –

3

我不知道如何解決這個問題。但我只是說

print("size of the array is \(self.categories?.count)") 

毗鄰

OperationQueue.main.addOperation{self.collectionView?.reloadData()} 

,並奇蹟般地工程..甚至想,當我回去,回來到屏幕上,它並沒有顯示任何東西。

我會更深入調查,試圖找出爲什麼發生這種情況

更新

使用

DispatchQueue.main.sync 

,而不是

DispatchQueue.main.async 

解決問題。

+1

@Sneak謝謝你的幫助!!!! –

+0

你好。我不明白你的意思是把這條線放在另一條線旁邊。你是說你在隊列呼叫之前放行嗎? – nyxee

+0

這個工作在Swift 4中非常棒! –

相關問題