How can I add a header view / top view (not section header) at the top of a UICollectionView
?
It should act excactly as UITableView
's tableHeaderView
property.
So it needs to sit on top of the first section header view (before the section at index 0), scroll along with the rest of the content, and have user interaction.
The best I've come up with so far is to make a special XIB (with MyCollectionReusableView
subclass of UICollectionReusableView
as the File's owner) for the first section header view that is big enough to also contain my subviews in header, it's kind of a hack, I think, and I haven't managed to detect touches.
Not sure if I can make my MyCollectionReusableView
subclass to allow touches or there's a better way.
Recently I was playing with support to add header and footer view to UITableView. However, task wasn't as easy as adding UITableViewCell s to the table view. Header and Footer views acts slightly different than regular table view cells.
Let's start by creating a UIView subclass with single label which will act as a HeaderView. We expect this UILabel to be multiline to demonstrate our ability to support self-sizing table view headers. Next, inside your viewDidLoad method add following piece of code to instantiate Component and assign it as a header view
First, let's start with a simple UITableView in the storyboard, pin it to all edges of its superview and connect IBOutlet inside the related UIViewController subclass. Since this is the header view for entire table view, we won't need any kind of reuse identifier since it will appear just once.
Ok, if you build and run the app it should look like this: Adding a header to the tableview in Interface Builder is easy, once you have your tableview drag a new view over the tableview towards the top, a blue line should appear, when it does you can place the view. See the below gif:
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height) collectionViewLayout:flowlayout]; self.collectionView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0); UIImageView *imagev = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"015.png"]]; imagev.frame = CGRectMake(0, -50, 320, 50); [self.collectionView addSubview: imagev]; [self.view addSubview: _collectionView];
I use the attribute contentInset
to insert a frame to the top of the UICollectionView
, then I add the image view to it, and it succeeds. I think it can act excactly as UITableView
's tableHeaderView
property. What do you think?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With