tim_yng tim_yng - 3 months ago 19
Swift Question

Swift UICollectionView header not appearing properly

The headers of the UICollectionView are not appearing properly. I have added one UILabel to the headers and it should display the section number. When I debug the viewForSupplementaryElementOfKind everything look alright. I have looked at different tutorials about collectionView headers and i can not find the error in my code. enter image description here

here is the entire code:

import UIKit

class ViewController: UIViewController {

var collectionView:UICollectionView!;

override func viewDidLoad() {
super.viewDidLoad()

let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20);
layout.itemSize = CGSize(width: 60, height: 60);
layout.headerReferenceSize = CGSize(width: CGRectGetWidth(self.view.bounds), height: 50);

collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout);


collectionView.dataSource = self;
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell");
collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header");
collectionView.delegate = self;
self.view.addSubview(collectionView);

}

}

extension ViewController:UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5;
}

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 10
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath);

cell.backgroundColor = UIColor.whiteColor();

return cell;
}




func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath)

view.backgroundColor = UIColor.blueColor();


let label = UILabel(frame: view.frame);
label.text = String(indexPath.section);
label.font = UIFont(name: "helvetica", size: 40);
label.textAlignment = .Center;
view.addSubview(label);



return view;

}


}

Answer

Replace the line

let label = UILabel(frame: view.frame);

with

let label = UILabel(frame: view.bounds);

Though you should note that you need to fix other issues with your code regarding reusing a supplementary view. I would recommend creating a subclass of UICollectionReusableView with a label inside instead of adding a new label manually from your data source.

Comments