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.Recently, our team was tasked with building a mobile app display that would show a grid with both horizontal and vertical scrolling along with varying cell sizes. The view would also require both a horizontal and vertical static header, similar to what users are used to seeing with spreadsheets and tables.
After some initial research and the advice of some colleagues, we decided to use the UICollectionView provided in iOS using the Swift development language. The example below shows our final product built using a custom implementation of the UICollectionViewLayout. Some extra features incorporated into the design included having cells that always stop decelerating at a predetermined interval 30 minutes and continuous scrolling up to the maximum amount of available guide data.
UICollectionView Tutorial: Getting Started
Upon further research, you will quickly learn that only one layout is predefined, that is the UICollectionViewFlowLayout. The Flow layout utilizes a line-wrapping style where items are placed one after the other until they reach the end of the figurative line, defined by the context size, and then wrap to the next line.
This is where many people end up on StackOverflow. Yes, absolutely! Except for the fine print: Our design required the collection to be scrolled both horizontally and vertically. The design also called for two more tricky traits:. Both the horizontal and vertical options are displayed below along with descriptions. A horizontally scrolling collection view with exactly enough items to fill the screen. A horizontally scrolling collection view with one extra item added to show the section-based line wrapping utilized by UICollectionViewFlowLayout.
A vertically scrolling collection view with exactly enough items to fill the screen. A vertically scrolling collection view with one extra item added to show the section-based line wrapping utilized by UICollectionViewFlowLayout.
Now what? By subclassing UICollectionViewLayout, we will take full control of the construction of the collection. This opens up the collection to horizontal and vertical scrolling and anything in between. To complete our custom design we will break the process into three tasks, building a custom layout, implementing sticky headers along both the x- and y-axis, and allowing independent cells to have unique size constraints. The layout will function by mapping the items into a pixel-based grid.
This will be the key to our varying size blocks and floating headers. After you download or create the starter project, you should be able to run the application on an iOS simulator and see an empty black screen resembling your empty collection view. Now we will want to hook that up to a beautiful collection. For the purpose of this blog post, we will use a simple cell with a label designating the section and item number. Start by adding another new Cocoa Touch class to your project.
We will use this file for managing outlet connections and providing some design flair providing visual feedback on cell sizes. These functions will provide a small black border around the cell.
The IBDesignable annotation will inform Interface Builder that you would like these design cues to be represented in the storyboard. Open up the storyboard and select the Collection View Cell.
In the Utilities Panel, switch to the Identity Inspector. This will allow our collection to reuse cells as they roll off screen instead of initializing a new cell for every object. Next, move over to the Size Inspector. Here you will want to define the width and height of the cell to and 30, respectively. These values are only used to assist in storyboard development.
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. I need a collection view to page through cells and center it like the App Store, where a portion of the previous and next cells look like this:.
The native isPagingEnabled flag would be great if it had an option to center on the cell. There are tons of hacks, articles, and suggestions out there that I've tried.
Many were overcomplicated or a horrible UX. I finally find a good balance with this example and adjusted the code. Do you have any suggestions or advice on how to simplify this or improve it? Sign up to join this community. The best answers are voted up and rise to the top.
Home Questions Tags Users Unanswered. Asked 1 year, 10 months ago. Active 1 year, 9 months ago. Viewed 6k times. TruMan1 TruMan1 61 1 1 silver badge 4 4 bronze badges. Active Oldest Votes. Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name.How To Use A UICollectionView To Replicate A Horizontal Paging UIScrollView In Swift Tutorial
Email Required, but never shown. The Overflow Blog. Featured on Meta. Community and Moderator guidelines for escalating issues via new response….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.
UICollectionView using horizontal and vertical scrolling with sticky rows and columns
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.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. Basically what we do is to calculate the item's sizes, to loop through all items and to calculate the item size, frame and the zIndex property to keep them visible.
Finally, we calculate the contentSize for the last item in order to calculate the total height of the content:. Well, these values are not significant, just keep in mind to set one greater that the other and both greater that zero. If you set the same value for these two zIndex, you are not preventing the first item from sticking:.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.
UICollectionView Tutorial: Getting Started
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.Its not a generic solution.
Even if i scrolled for the first time the condition if scrollView. All rights reserved.
Building a Multi-Directional UICollectionView in Swift
Thanks, man, for sharing It helps a lot!! Anyone can check my project below. Infinitely loop through views, recycle views, automatically fits current view on center, and so on. First I want to thank you for your nice and effective code.
I have also found another project, implementing similar strategy for infinite scroll but I noticed in both projects small fluctuating shivering of images just a bit before scroll will stop.
Do you have any advice hot to prevent this? Thank you, Marko. Please try this drive. You can add more items in collection view data source by adding images. Here we will play with UIScrollView delegate methods. In this sample video you can see how image gallery can be implemented in iPhone using horizontal scrolling.
Then download the resource pack for this project e. If you have basic knowledge of Autolayout then you can add constraints on collection view. So far you have added views for you project. You will see that the class has the following code in it already:. In InfiniteScrollingViewController. Name the file InfiniteScrollingCell. To understand code in detail.
Common Utility Extensions in Swift Utils. Swift For-Loops. Subscribe to our Blog. Subscribe to our blog.