2014-06-12 4 views
4

В моем проекте я создал ячейку в UICollectionViewCellUICollectionView Использования Swift

Ее получила прерывающую ошибку приложение из-за неперехваченное исключением

Кодекса следующим образом.

GalleryCell.swift

class GalleryCell: UICollectionViewCell 
{ 


@IBOutlet var titleLabel : UILabel 


init(coder aDecoder: NSCoder!) 
{ 
    super.init(coder: aDecoder) 
} 
} 

и я использовал эту ячейку в Мой ViewController:

Код следующим образом:

NextViewController.swift

import UIKit 

class NextViewController: UIViewController 
{ 

@IBOutlet var collectionView : UICollectionView 



var ListArray=NSMutableArray() 



override func viewDidLoad() 
{ 
    super.viewDidLoad() 


    for i in 0..70 
    { 
     ListArray .addObject("C: \(i)") 
    } 




} 



    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section:Int)->Int 
    { 
     return ListArray.count 
    } 


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell 
{ 

    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as GalleryCell 


    cell.titleLabel.text="\(ListArray.objectAtIndex(indexPath.item))" 

    return cell 
} 


func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize 
{ 

    return CGSizeMake(66, 58) 
} 



override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

}

Мой вопрос я получаю следующее сообщение об ошибке:

***** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CELL - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'*** First throw call stack:** 

ответ

16

я добавил следующие две строки в NextViewController.swift под viewDidLoad():

var nibName = UINib(nibName: "GalleryCell", bundle:nil) 

collectionView.registerNib(nibName, forCellWithReuseIdentifier: "CELL") 

Проблема заключалась в том, что я не регистрировал перо. Теперь, когда я это делаю, он работает нормально.

2

Вы должны зарегистрировать класс клеток.

В вашем viewDidLoad пишите.

collectionView.registerClass(NSClassFromString("GalleryCell"),forCellWithReuseIdentifier:"CELL"); 

Prior to calling the dequeueReusableCellWithReuseIdentifier:forIndexPath: method of the collection view, you must use this method or the registerNib:forCellWithReuseIdentifier: method to tell the collection view how to create a new cell of the given type. If a cell of the specified type is not currently in a reuse queue, the collection view uses the provided information to create a new cell object automatically.

If you previously registered a class or nib file with the same reuse identifier, the class you specify in the cellClass parameter replaces the old entry. You may specify nil for cellClass if you want to unregister the class from the specified reuse identifier.

Ссылка registerClass:forCellWithReuseIdentifier:

+0

Его получение следующей ошибки Завершение приложения из-за неперехваченного исключения «NSInternalInconsistencyException», причина: «попытаться зарегистрировать класс ячеек, который не является подклассом UICollectionViewCell ((null)) ' – PREMKUMAR

+0

@PREMKUMAR: Проверьте свой класс GalleryCell. Вы сделали это как подкласс UICollectionViewCell? Проблема в самом журнале –

+0

Спасибо, что я получаю ответ. Спасибо, что потратили свое драгоценное время. – PREMKUMAR

4

то же самое для верхнего/нижнего колонтитула в скор:

// register header accessory view: 
    self.collectionView.registerClass(UICollectionReusableView.self, 
     forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, 
     withReuseIdentifier: headerReuseIdentifier); 
0

Я хотел бы добавить еще один ответ, который помог мне, в случае, если он становится полезным для кого-то другого.

Кажется, что все остальные решили эту проблему с помощью registerNib:forCellWithReuseIdentifier: или registerClass:forCellWithReuseIdentifier:. Для меня было другое решение: в моей раскадровке я выбрал заголовок и просмотрел в Identity Inspector в верхней части, где у него есть поля для моего пользовательского класса. В частности, поле было пустым. Мне нужно было снять стрелку рядом с этим полем и выбрать нужную цель.

Как только я это сделал, & сохранил раскадровку, вышеупомянутый сбой больше не состоялся, и я мог видеть свой пользовательский заголовок.

Смежные вопросы