[英]Swift collectionView non reusable cell
我有一個帶有2個部分的collectionView,每個部分應基於同一單元格(僅包含UIImageView)。 這些部分之間的唯一區別是它們應包含的單元格數量和顯示的圖像類型。
如果將cellforItemAtIndexPath方法設置為使用出隊的單元格(collectionView.dequeueReusableCellWithIdentifier),則所有填充都很好,如果將其設置為使用自定義單元格的實例而不出隊,則會崩潰。
cellForItemAtIndexPath方法:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//cannot use dequedReusableCell since some cells below scroll-line should remain highlighted
let cell = NumbersCollectionViewCell() // CAUSES CRASH
// let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.cellIdentifier, forIndexPath: indexPath) as! NumbersCollectionViewCell // WORKS FINE
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
NumbersCollectionViewCell定義:
class NumbersCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
出現的錯誤是:“致命錯誤:在展開可選值時意外發現nil”,它突出顯示了我的cellForItemAtIndexPath方法中的“ case 0”行。
我不想使用出隊單元格的原因是,我需要根據用戶的選擇在運行時突出顯示某些單元格,並且如果我使用出隊單元格,似乎並沒有將其保持在滾動行突出顯示。
假設你有一個既.swift
和.xib
為你的文件,你需要實例化NumbersCollectionViewCell
這樣的:例如,
let numbersCollectionViewCell = UINib(nibName: "NumbersCollectionViewCell", bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as! NumbersCollectionViewCell
否則,您的IBOutlet
不會被連接。
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier: "NumbersCollectionViewCell">, forIndexPath: NSIndexPath>) as? NumbersCollectionViewCell else {
print("failed to get cell")
return UICollectionViewCell()
}
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.