If you're not familiar with UICollectionViewI'd suggest to get familiar with this class immediately. They're the basic building blocks for many apps provided by Apple and other third party developers. It's like UITableView on steroids.
Here is a quick intro about how to work with them through IB and Swift code. You might have noticed that I have a love for metal music. In this tutorial we're going to build an Apple Music catalog like look from ground zero using only the mighty UICollectionView class.
Headers, horizontal and vertical scrolling, circular images, so basically almost everything that you'll ever need to build great user interfaces. In a nuthsell, the data source will provide all the required data about how to populate the collection view, and the delegate will handle user events, such as tapping on a cell. You should have a clear understanding about the data source and delegate methods, so feel free to play with them for a little while.
As you might have noticed cells are the core components of a collection view. They are derived from reusable views, this means that if you have a list of elements, there won't be a thousand cells created for every element, but only a few that fills the size of the screen and when you scroll down the list these items are going to be reused to display your elements. This is only because of memory considerations, so unlike UIScrollView the UICollectionView and UITableView class is a really smart and efficent one, but this is also the reason why you have to prepare reset the contents of the cell every time before you display your actual data.
Initialization is also handled by the system, but it's worth to mention that if you are working with Interface Builder, you should do your customization inside the awakeFromNib method, but if you are using code, init frame: is your place. Next we have to implement the view controller which is responsible for managing the collection view, we're not using IB so we have to create it manually by using Auto Layout anchors - like for the textLabel in the cell - inside the loadView method.
After the view hierarchy is ready to rock, we also set the data source and delegate plus register our cell class for further reuse. Note that this is done automatically by the system if you are using IB, but if you prefer code you have to do it by calling the proper registration method.
You can register both nibs and classes. This time you should pay some attention on the flow layout delegate methods. You can use these methods to provide metrics for the layout system. The flow layout will display all the cells based on these numbers and sizes. So in this section I'm going to both use storyboards, nibs and some Swift code.
This is my usual approach for a few reasons. Altought I love making constraints from code, most people prefer visual editors, so all the cells are created inside nibs.
Why nibs? Becuase if you have multiple collection views this is "almost" the only nice way to share cells between them. You can create section footers exactly the same way as you do headers, so that's why this time I'm only going to focus on headers, because literally you only have to change one word in order to use footers. You just have to create two xib files, one for the cell and one for the header. Please note that you could use the exact same collection view cell to display content in the section header, but this is a demo so let's just go with two distinct items.One of the realities of working in app development is overcoming the daily challenges that come our way.
One of our most recent challenges was a tableview which could be scrolled both horizontally and vertically. In addition, the first column needed to remain static when scrolled horizontally and the first row when vertically. Finally, we needed this tableview to contain a large amount of data, so it was crucial it scrolled smoothly. We started thinking on a UITableView inside an UIScrollView, but after some attempts we realised it was tricky task customising it in terms of scrolling and sticking cells.
It was really painful to work with the UITableView to make the necessary customisation. So, we decided to change to UICollectionView, which is much more customisable.
Unfortunately, the grid layout scrolls along one axis only; either horizontally or vertically. The definitive solution was to subclass the UICollectionViewLayout class, which allowed the required customisation we needed.
Place a UICollectionView in our desirable nib file. Set some properties in the Attributes Inspector. Otherwise, you could scroll in both directions at the same time. In our collection view the sections are denoted as row and the rows as columns, so keep this in mind to set the number of sections and items. It depends on the collection view flow layout direction we set. Once you finished to set the collection view methods, we need to set the custom collection view layout we created.
Firstly, we need to set three properties to manage all the data:. If you want to set custom sizes for the items, you need to set the following method:. I highly recommend you store the calculated sizes on itemsSize array in order to do the calculations only once per column. Otherwise it could slow the performance! You need this to stick the headers! Subclasses must override this method and use it to return layout information for all items whose view intersects the specified rectangle.
Your implementation should return attributes for all visual elements, including cells, supplementary views, and decoration views. You need to return the layout attributes for a given indexpath, so return the corresponding item attributes with this method:. This will be called every time we need to redraw the collection view. Firstly, we ensure we have the required data to be shown, otherwise we return void:. Now we must check if we'e calculated the item's attributes.
In affirmative case, we are going to use these attributes to stick the headers step Otherwise we need to calculate the attributes for the first time and save them in the itemAttributes array.An object that manages an ordered collection of data items and presents them using customizable layouts. The collection view gets its data from the data source object, which is an object that conforms to the UICollection View Data Source Protocol and is provided by your app.
Data in the collection view is organized into individual items, which can then be grouped into sections for presentation. An item is the smallest unit of data you want to present. For example, in a photos app, an item might be a single image. The collection view presents items onscreen using a cell, which is an instance of the UICollection View Cell class that your data source configures and provides.
In addition to its cells, a collection view can present data using other types of views too. These supplementary views can be things like section headers and footers that are separate from the individual cells but still convey some sort of information. Besides embedding it in your user interface, you use the methods of UICollection View object to ensure that the visual presentation of items matches the order in your data source object.
Thus, whenever you add, delete, or rearrange data in your collection, you use the methods of this class to insert, delete, and rearrange the corresponding cells. You also use the collection view object to manage the selected items, although for this behavior the collection view works with its associated delegate object. A very important object associated with a collection view is the layout object, which is a subclass of the UICollection View Layout class.
The layout object is responsible for defining the organization and location of all cells and supplementary views inside the collection view. Although it defines their locations, the layout object does not actually apply that information to the corresponding views. Because the creation of cells and supplementary views involves coordination between the collection view and your data source object, the collection view actually applies layout information to the views.
Thus, in a sense, the layout object is like another data source, only providing visual information instead of item data. You normally specify a layout object when creating a collection view but you can also change the layout of a collection view dynamically. The layout object is stored in the collection View Layout property. Setting this property directly updates the layout immediately, without animating the changes. If you want to create an interactive transition—one that is driven by a gesture recognizer or touch events—use the start Interactive Transition to: completion: method to change the layout object.
UICollectionView using horizontal and vertical scrolling with sticky rows and columns
That method installs an intermediate layout object whose purpose is to work with your gesture recognizer or event-handling code to track the transition progress. When your event-handling code determines that the transition is finished, it calls the finish Interactive Transition or cancel Interactive Transition method to remove the intermediate layout object and install the intended target layout object.The iOS Photos app has a stylish way of displaying photos via a multitude of layouts.
You can view your photos in a nice grid view:. You can even transition between the two layouts with a cool pinch gesture. UICollectionView makes adding your own custom layouts and layout transitions like those in the Photos app simple to build. You can use them to make circle layouts, cover-flow style layouts, Pulse news style layouts — almost anything you can dream up!
Using them is very similar to the table view data source and delegate pattern. First, take a look at the example of the finished project. UICollectionView contains several key components, as you can see below:. In addition to the visual components described above, a collection view has a layout object which is responsible for the size, position and several other attributes of the content.
Layouts can be swapped out during runtime, and the collection view can even automatically animate switching from one layout to another! Elements lay out one after another based on their size, quite like a grid view. You can use this layout class out of the box, or subclass it to get some interesting behavior and visual effects.
You will learn more about these elements in-depth throughout this tutorial. It will allow you to search for a term on the popular photo sharing site Flickr, and it will download and display any matching photos in a grid view, as you saw in the screenshot above. Ready to get started? Open the FlickrSearch starter project.
Project files can be downloaded at the top or bottom of this tutorial using the Download Materials button. Have a look around before you go any further. Open Main. Next, select the Navigation Controller you installed and make it the initial view controller in the Attributes inspector :.
Focusing on the collection view controller, select the UICollectionView inside, and change the background color to White Color :. Conversely, a horizontal flow layout places items from top to bottom across the left edge of the view until it reaches the bottom edge. Select the single cell in the collection view and set the Reuse Identifier to FlickrCell using the Attributes inspector. This should also be familiar from table views — the data source will use this identifier to dequeue or create new cells.
Drag a text field into the center of the navigation bar above the collection view. This will be where users enter their search text. Next, control-drag from the text field to the collection view controller and choose the delegate outlet:. UICollectionViewController does a lot, but you generally need to make a subclass. Do this now. The template has a lot of code, but the best way to understand what this it does is to start from scratch.
Open FlickrPhotosViewController. Go back to Main. Flickr is a wonderful image-sharing service that has a publicly accessible and dead-simple API for developers to use. With the API, you can search for photos, add photos, comment on photos, and much more.Create a single view project in Objective C and open the Storyboard.
This can be done in File Inspector View on the right. In the general settings under Deployment info, un-tick the boxes for portrait and upside down so the app can only be displayed horizontally. Try to centre it in the middle of the View. Make sure items is set to 1 while you are there so that a prototype cell stays in the collection. I would now add some views and labels to the default prototype cell so that what you are working with is realistic.
Here is my collection View and cell. Pretty much the same as a tableView Delegate. Now build and run the project. You should see something similar to the below. If not, put a breakpoint in the delegate methods and make sure they are called and the delegate is setup correctly. You will notice I have hardcoded in all of the width values but that is just to make this more understandable, it should be quite simple to get the values at run time programmatically.
So you should now adapt your ViewController to look like the below. There is no reason to use that many lines of code or to have both a left and right inset other than simplicity for this demonstration.
That method can be reduced to a few lines at most. Run the project again and you should have a centred UICollectionView like below. You are commenting using your WordPress. You are commenting using your Google account. You are commenting using your Twitter account. You are commenting using your Facebook account.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I have successfully implemented a UICollectionView. Is it possible to change the scrollDirection? Learn more. Ask Question.
Asked 4 years, 7 months ago. Active 2 years, 5 months ago. Viewed 33k times. Can you please show how to implement it programmatically? LinusGeffarth Entitize Entitize 2, 3 3 gold badges 11 11 silver badges 28 28 bronze badges.
Active Oldest Votes. Jack 9, 4 4 gold badges 50 50 silver badges 78 78 bronze badges. Sash Zats Sash Zats 4, 1 1 gold badge 24 24 silver badges 40 40 bronze badges. Sign up or log in Sign up using Google. Sign up using Facebook.
Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Podcast Programming tutorials can be a real drag.
Ultimate UICollectionView guide with iOS examples written in Swift
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I have successfully implemented a UICollectionView. Is it possible to change the scrollDirection? Learn more. Ask Question. Asked 4 years, 7 months ago. Active 2 years, 5 months ago. Viewed 33k times. Can you please show how to implement it programmatically?
LinusGeffarth Entitize Entitize 2, 3 3 gold badges 11 11 silver badges 28 28 bronze badges. Active Oldest Votes. Jack 9, 4 4 gold badges 49 49 silver badges 77 77 bronze badges. Sash Zats Sash Zats 4, 1 1 gold badge 24 24 silver badges 40 40 bronze badges.
scrolling not working in UICollectionView
Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Podcast Cryptocurrency-Based Life Forms.
Q2 Community Roadmap.