2017-05-11 221 views
3

我在基本ViewController中實現UICollectionView(collectionView) 我的集合視圖必須像在numbersofItemInSection代碼中那樣檢索5個單元格。 顯示CollectionView並調用numbersofItemInSection函數,但未調用cellForItemAt函數,因此集合視圖爲空。UICollectionView cellForItem not called

import UIKit 


private let reuseIdentifier = "Cell" 



class TestViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{ 

    lazy var collectionView : UICollectionView = { 
     let layout = UICollectionViewFlowLayout() 
     let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) 
     cv.translatesAutoresizingMaskIntoConstraints = false 
     cv.delegate = self 
     cv.dataSource = self 
     return cv 
    }() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Register cell classes 
     self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 

     collectionView.backgroundColor = .white 
     navigationItem.title = "test" 

     setupViews() 
    } 

    func setupViews(){ 
     view.addSubview(collectionView) 

     collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true 
     collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true 
     collectionView.heightAnchor.constraint(equalToConstant: 60).isActive = true 
     collectionView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 5 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) 
     // Configure the cell 

     cell.backgroundColor = .red 

     return cell 
    } 


} 
+0

它確實按預期工作。 http://imgur.com/a/IYslT –

+0

你用xib使用單元格嗎? – KKRocks

+0

@SaurabhYadav是否有可能是我的Xcode設置?因爲我昨天安裝了Xcode 7,所以我現在有2個Xcode應用程序。 – zorobabel

回答

0

它是你的collectionView的高度或collectionView的框架問題,那麼你需要設置適當的高度collectionView。

OR

試試這個

 override func viewDidLoad() { 
       super.viewDidLoad() 
       navigationItem.title = "test" 

       setupViews() 
       collectionView.backgroundColor = .white 
       self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 
// remove this line if you not use xib 

      } 
+0

你是對的@KKRocks我只是增加我的集合視圖高度和細胞出現。 感謝所有:) – zorobabel

+0

歡迎@ zorobabel – KKRocks

0

我檢查你的代碼,它是工作u的使用迅速fine.As 3,所以你將不得不使用Xcode的8 +與.RUN它XCODE 8,因爲語法是swift 3,你會得到結果。