Ошибка приведения значения типа "UICollectionReusableView" к "MyApp.CSSectionHeader"
У меня есть следующий класс:
class CSSectionHeader: UICollectionReusableView {
@IBOutlet var textLabel: UILabel!
}
Затем я пытаюсь разыграть его следующим образом:
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let cell1 = UICollectionReusableView()
if (kind == UICollectionElementKindSectionHeader) {
// Throws the cast error here:
let cell: CSSectionHeader = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "sectionHeader", forIndexPath: indexPath) as! CSSectionHeader
return cell
} else if (kind == CSStickyHeaderParallaxHeader) {
let cell: UICollectionReusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! UICollectionReusableView
return cell
}
return cell1
}
Проблема в том, что я получаю следующую ошибку:
Could not cast value of type 'UICollectionReusableView' (0x10ff4d140) to 'MyApp.CSSectionHeader' (0x10d775a70).
2 ответа
Решение
Чтобы иметь возможность удалить заголовок вашего пользовательского класса, вы должны зарегистрировать этот класс в collectionview перед вызовом dequeueReusableSupplementaryViewOfKind
,
Это должно выглядеть так:
self.collectionView.registerClass(CSSectionHeader.self,
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "sectionHeader")
Вы можете разместить его внутри viewDidLoad()
Вы также можете установить собственный класс для заголовка в раскадровке. Это пригодится, если вы добавляете делегата Flow Layout через расширение.
Swift 3 в viewDidLoad()
self.collectionView.registerClass(CSSectionHeader.self,
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "sectionHeader")
Также добавьте следующее
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView{
let headerView: CSSectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:"sectionHeader", for: indexPath) as! CSSectionHeader
return headerView }