Thiha Aung
Thiha Aung

Reputation: 5106

How to add UIButton to UICollectionView which will scroll with its cell?

I was trying to build home base application which mean there are many icon at root view and it will navigate to appropriate view. So, I will use collection view for it. But, the problem is when I add button to the collection view, the button didn't scroll with collection view, when I scroll collection view up. Here is my simulator build:

enter image description here

As you can see,the button "Click here to login" didn't scroll up with collection view. So, is there any way that I can add button to center of collection view which will scroll with collection view?

Here is my storyboard :

storyboard

What am I doing wrong?

Upvotes: 1

Views: 591

Answers (1)

Mischa
Mischa

Reputation: 17269

When you take a closer look at your view hierarchy in Interface Builder you'll notice that the button you added isn't actually a subview of your collection view. I added a red line to indicate which objects belong to the collection view.


View Hierarchy (wrong)


Your login button is on the same level as your collection view in the view hierarchy. Both are subviews of your view controller's root view. So no wonder the button doesn't scroll with the collection view.

However, you cannot simply add an arbitrary view (or button) to the collection view itself in Interface Builder. You'll need to add a Collection Reusable View first as your collection view header and then add your button to it.

Collection Reusable View

Your storyboard scene in Interface Builder will then look like this:


View Hierarchy (right)


Please note that you'll also need to add some code to your collection view data source (which will probably be the same as your collection view controller) in order to make this work.

Upvotes: 4

Related Questions