我在基本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
}
}
它確實按預期工作。 http://imgur.com/a/IYslT –
你用xib使用單元格嗎? – KKRocks
@SaurabhYadav是否有可能是我的Xcode設置?因爲我昨天安裝了Xcode 7,所以我現在有2個Xcode應用程序。 – zorobabel