iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

时间:2022-02-14 23:28:46

In this tutorial, we will build a simple app to display a collection of recipe photos in grid layout. Here are what you’re going to learn:

  1. Introduction to UICollectionView
  2. How to Use UICollectionView to build a simple Grid-based layout
  3. Customizing the Collection Cell Background

Create Simple App with Grid Layout

To better understand how UICollectionView work, let’s get some hand-on experience and build a simple app. Open Xcode and create a new project using the “Single View application” template. Name the project as “RecipePhoto” with “Use Storyboard” and “Use Automatic Reference Count” enabled.

Note: Please make sure you use Xcode 4.5 or up to create the project.
iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

RecipePhoto – New Xcode Project

Designing the Collection View

Go to Storyboard and delete the default view controller. Instead, add a Collection View Controller from object library.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Add a Collection View Controller

In the “Size Inspector” of the Collection View, you can change various size-related attributes. Let’s alter the size of the cell and change it to 100 by 100 pixels.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Change the size of Collection View Cell

Next, select the Collection View Cell and set the identifier as “Cell” in the Attribute Inspector.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Cell Reuse Identifier

Then, add an Image View to the cell. Xcode automatically resizes the image view and make it fit into the cell. In the “Attribute Inspector”, set the tag value to 100 for later reference.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Add Image View to Cell

Coding the Collection View

In Project Navigator, right-click and select “New File”. Create a new class that is a subclass of UICollectionViewController and name it as RecipeCollectionViewController.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Create RecipeCollectionViewController

Go back to Storyboard and assign it as the custom class of the Collection View Controller.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Assign RecipeCollectionViewController as the custom class

As said, the UICollectionView operates in a very similar way to UITableView. To populate data in UITableView, we have to implement two methods defined in the UITableViewDataSource protocol. Much like the UITableView, the UICollectionViewDataSource protocol defines data source methods for providing the data of the collection view. At least, you have to implement the collectionView:numberOfItemsInSection: and collectionView:cellForItemAtIndexPath: methods.

Let’s move on to code the RecipeCollectionViewController class. First, download this image pack, unzip it and add all the images into the Xcode project.

In RecipeCollectionViewController.m, declare an array for the image files:

1
2
3
@interface RecipeCollectionViewController () {
    NSArray *recipePhotos;
}

And initialize it in viewDidLoad method:

1
2
3
4
5
6
7
8
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Initialize recipe image array
    recipeImages = [NSArray arrayWithObjects:@"angry_birds_cake.jpg", @"creme_brelee.jpg", @"egg_benedict.jpg", @"full_breakfast.jpg", @"green_tea.jpg", @"ham_and_cheese_panini.jpg", @"ham_and_egg_sandwich.jpg", @"hamburger.jpg", @"instant_noodle_with_egg.jpg", @"japanese_noodle_with_pork.jpg", @"mushroom_risotto.jpg", @"noodle_with_bbq_pork.jpg", @"starbucks_coffee.jpg", @"thai_shrimp_cake.jpg", @"vegetable_curry.jpg", @"white_chocolate_donut.jpg", nil];

}

Next, implement the two mandatory methods of UICollectionViewDataSource protocol:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return recipeImages.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]];
    
    return cell;
}

The collectionView:numberOfItemsInSection: method returns the number of recipe images. The cellForItemAtIndexPath: method provides the data for the collection view cells. We first define a cell identifier and then request the collectionView to dequeue a reusable cell using that reuse identifier. In iOS 6, you no longer need to create the cell manually. The dequeueReusableCellWithReuseIdentifier: method will automatically create a cell or return you with a cell from re-use queue. At last, we get the image view by using the tag value and assign it with a recipe image.

Now compile and run the app. You should have a grid-based photo app.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

RecipePhoto App with Grid-based Layout

Customizing the Collection Cell Background

Isn’t UICollectionView great? With a few lines of code, you can create a grid-based photo app. But what if you want to add a picture frame to the photos? Like other UI elements, the design of the collection view cell lets developers customize the background easily. The UICollectionViewCell is actually comprised of three different views including background, selected background and content view. It’s best to illustrate the cell views using a picture:
iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

  • Background View – background view of the cell
  • Selected Background View – the background view when the cell is selected. When user selects the cell, this selected background view will be layered above the background view.
  • Content View – obviously, it’s the cell content.

We have already used the content view to display the recipe photo. We’ll make use of the background view to show the picture frame. In the image pack you downloaded earlier, it includes a file named “pic_frame.png”, which is the picture frame. The size of the frame is 100 by 100 pixel. In order to frame the recipe photo, we’ll first resize the image view of cell and re-arrange its position.

Go to Storyboard and select the image view. Set X to 5 and Y to 8. The width and height should be changed to 90 and 72 pixels respectively.

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

Resize image view to fit into the photo frame

In the cellForItemAtIndexPath: method of RecipeCollectionViewController.m, add the following line of code:

1
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];

We first load the photo frame image and set it as the cell background. Now compile and run the app again. Your app should look like this:

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6的更多相关文章

  1. iphone Dev 开发实例10:How To Add a Slide-out Sidebar Menu in Your Apps

    Creating the Xcode Project With a basic idea about what we’ll build, let’s move on. You can create t ...

  2. iphone Dev 开发实例8: Parsing an RSS Feed Using NSXMLParser

    From : http://useyourloaf.com/blog/2010/10/16/parsing-an-rss-feed-using-nsxmlparser.html Structure o ...

  3. iphone dev 入门实例6:How To Use UIScrollView to Scroll and Zoom and Page

    http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content Getting Starte ...

  4. iphone dev 入门实例5:Get the User Location & Address in iPhone App

    Create the Project and Design the Interface First, create a new Xcode project using the Single View ...

  5. iphone dev 入门实例4:CoreData入门

    The iPhone Core Data Example Application The application developed in this chapter will take the for ...

  6. iphone dev 入门实例1:Use Storyboards to Build Table View

    http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/ Creating Navig ...

  7. iphone dev 入门实例7:How to Add Splash Screen in Your iOS App

    http://www.appcoda.com/how-to-add-splash-screen-in-your-ios-app/ What’s Splash Screen? For those who ...

  8. iphone dev 入门实例2:Pass Data Between View Controllers using segue

    Assigning View Controller Class In the first tutorial, we simply create a view controller that serve ...

  9. iphone dev 入门实例3:Delete a Row from UITableView

    How To Delete a Row from UITableView I hope you have a better understanding about Model-View-Control ...

随机推荐

  1. 每天一点Android干货-Activity的生命周期

    Activity Activity是这样一个程序组件,它为用户提供一个用于任务交互的画面. 一个应用程序通常由多个activity组成,它们彼此保持弱的绑定状态.典型的,当一个activity在一个应 ...

  2. linux whoami命令

    whoami显示的是当前"操作用户"的用户名.

  3. Javascript重要知识点梳理

    Javascript重要知识点梳理 一.Javascript流程控制 js中常用的数据类型 var关键字的使用 if – else if – else switch while for 二.Javas ...

  4. SharedSDK微信分享不成功,分享之后没有反应

    对于一般来说,使用SharedSDK的时候,分享不成功不外乎下面几个原因: 1.测试没有打包2.打包的keystore跟微信开放平台上面的不一致, 导致MD5码不一致3.分享参数错误4.应用没有审核通 ...

  5. CmdParse

    Procedure URPOSE Uses Dos,Crt; Const VersionNum = 'V1.0 BETA'; ProgNameStr = 'NEWPROJ.EXE'; ProgName ...

  6. Java调度线程池ScheduledThreadPoolExecutor源码分析

    最近新接手的项目里大量使用了ScheduledThreadPoolExecutor类去执行一些定时任务,之前一直没有机会研究这个类的源码,这次趁着机会好好研读一下. 该类主要还是基于ThreadPoo ...

  7. [转]搭建Hadoop伪分布式环境

    https://my.oschina.net/MyHeaven1987/blog/1821509 http://hadoop.apache.org/docs/current/hadoop-projec ...

  8. linux 安装svn客户端

    安装命令:yum install -y subversion 客户端使用命令: svn help  帮助命令 svn checkout --help  子帮助命令

  9. Dapper Extensions Change Schema

    Dapper Extensions Change Schema You can use the AutoClassMapper to assign a new schema to your model ...

  10. 解决 java.lang.ClassNotFoundException: javax.servlet.ServletContext报错

    原因:tomcat找不到servlet,即缺少了servlet-api.jar包 解决方法: 我的项目是用maven搭建的 在pom.xml中加入依赖 <dependency> <g ...