1
我有一個UICollectionView
,我添加到我的故事板中的UIViewController
。cellForItemAtIndexPath從不叫
它包含BookCell
類的UICollectionViewCell
和可重複使用的標識符BookCell
。
bookArray
在prepareForSegue
方法被傳遞從以前的ViewController
cellForItemAtIndexPath
不會被調用。我試圖在Storyboard和viewDidLoad
中聲明BookCollectionVC
作爲delegate和dataSource,正如你可以看到的那樣,但是這並沒有改變任何東西。
我已經閱讀了關於單元格大小的多個SO答案,以該部分中的項目數量爲例說明了delegate
和dataSource
的多種方式,並嘗試了所有這些方法。
任何想法?
class BookCollectionVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collection: UICollectionView!
var bookArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// collection.delegate = self
// collection.dataSource = self
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BookCell", forIndexPath: indexPath) as? BookCell {
// This never gets called
let bookIsbn = bookArray[indexPath.row]
cell.configureCell(bookIsbn)
return cell
} else {
return UICollectionViewCell()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(bookArray.count)
return bookArray.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let cellWidth = screenWidth/4
return CGSizeMake(cellWidth,cellWidth)
}
你可以檢查項目到'bookArray'數組嗎? – deoKasuhal
你是什麼意思檢查項目'成''? @Dev –
如果沒有項目到'bookArray'中,那麼'cellForItemAtIndexPath'永遠不會被調用。在示例代碼中,您將'bookArray'分配爲空數組。你需要確保'bookArray'有一些對象,以便'cellForItemAtIndexPath'方法被執行。 – deoKasuhal