2017-02-13 3 views
3

Я пытаюсь добавить заголовок в collectionView с помощью пользовательского xib-файла. Я создал файл xib с использованием класса UICollectionReusableView. В collectionViewController Я зарегистрировал xib файл вроде этого:Добавить пользовательский заголовок в коллекцию view swift

self.collectionView.register(UINib(nibName: HCollectionReusableView.nibName, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HCollectionReusableView.reuseIdentifier) 

и после этого в viewForSupplementaryElementOfKind я

let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HCollectionReusableView.reuseIdentifier, for: indexPath) as! HCollectionReusableView 

и для проклейки

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 
    return CGSize(width: 100, height: 50) 
} 

я получаю сообщение об ошибке: Не удалось загрузить NIB в пакете. любой недостающий код?

HCollectionReusableView класс:

class HCollectionReusableView: UICollectionReusableView { 

static var nibName : String 
    { 
    get { return "headerNIB"} 
} 

static var reuseIdentifier: String 
    { 
    get { return "headerCell"} 
} 



override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

}

ответ

6

Вам нужно позвонить viewForSupplementaryElementOfKind так:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 

    switch kind { 
    case UICollectionElementKindSectionHeader: 
      let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HCollectionReusableView", for: indexPath) as! HCollectionReusableView 

      reusableview.frame = CGRect(0 , 0, self.view.frame.width, headerHight) 
     //do other header related calls or settups 
      return reusableview 


    default: fatalError("Unexpected element kind") 
    } 
} 

Таким образом, вы можете инициализировать и показать заголовке

Другой способ установки UICollectionViewHeader кадр является путем расширения UICollectionViewDelegateFlowLayout, как это :

extension UIViewController: UICollectionViewDelegateFlowLayout { 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 
     return CGSize(width: collectionView.frame.width, height: 100) //add your height here 
    } 
} 

Это устраняет необходимость вызова:

reusableview.frame = CGRect(0 , 0, self.view.frame.width, headerHight) 

В вышеуказанном func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView

Remember to register the HeaderView after you initialise your UICollectionView by calling:

collectionView.register(UINib(nibName: HCollectionReusableView.nibName, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HCollectionReusableView")

+0

Я думаю, что я должен измените регистрацию xib на класс, вот теперь ошибка: не удалось удалить вид вида: UICollectionElementKindSectionHeader с идентификатором HCollectionReusableView - должен зарегистрировать nib или класс для идентификатор или соединить прототип ячейки в раскадровке (null) –

+1

вы получаете ошибку, так как идентификаторы, когда вы декалируете элемент и когда вы регистрируете, не совпадают ... попробуйте жестко указать идентификатор, как это, когда вы зарегистрируете ячейку: 'self.collectionView.register (UINIB (nibName: HCollectionReusableView.nibName, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier:" HCollectionReusableView ") ' это должно работать ... тогда вы можете просто скорректировать код в соответствии с вашими потребностями – John

+0

вы зарегистрируете класс только в том случае, если вы вообще не используете Xib или Storyboard – John

0

Вы установили файл»параметр Owner в вашем XIb файле? Измените владельца файла на контроллер View View.

enter image description here

+0

да я, в владельце файла и в коллекции многоразового зрения –

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