iOS UICollectionView示例教程

In this tutorial we’ll look into iOS UICollectionView component and develop a basic application out of it.

在本教程中,我们将研究iOS UICollectionView组件并从中开发一个基本应用程序。

UICollectionView (UICollectionView)

UICollectionView is similar to UITableView except the fact that it’s more customisable. The main difference between a UICollectionView and a UITableView is that a UICollectionView can display more than one column and it supports horizontal scrolling.

UICollectionView与UITableView相似,不同之处在于它更具可定制性。 UICollectionView和UITableView之间的主要区别在于,UICollectionView可以显示多个列,并且支持水平滚动。

A UICollectionView is used to customise the layout in any way we wish. The basic UICollectionView resembles to a GridView from android in many ways.

UICollectionView用于以我们希望的任何方式自定义布局。 基本的UICollectionView在许多方面类似于android的GridView。

The most common place where a UICollectionView layout is seen is in the Photos App.

在“照片”应用中可以看到UICollectionView布局的最常见位置。

UICollectionView组件 (UICollectionView components)

UICollectionView consists of the following major components.

UICollectionView包含以下主要组件。

  1. UICollectionViewCell : Just like UITableViewCells, these cells are the subviews of the UICollectionView. Our content is displayed in these cells only. The cells are dequeued as the user leaves the screen

    UICollectionViewCell :就像UITableViewCells一样,这些单元格是UICollectionView的子视图。 我们的内容仅显示在这些单元格中。 用户离开屏幕时,单元格已出队
  2. Supplementary Views : It consists of other important components such as labels, section headers and footers that are used to define and divide the content area

    补充视图 :它由其他重要组成部分,例如标签,节的页眉和页脚,用于定义和划分内容区域

UICollectionView示例 (UICollectionView Example)

Let’s take advantage of Storyboards to implement a Collection View in our View Controller.

让我们利用情节提要板在我们的View Controller中实现一个Collection View。

For that drag the Collection View onto the View Controller and drag it to cover the full screen below the navigation bar.

为此,将“集合视图”拖动到“视图控制器”上,然后将其拖动以覆盖导航栏下方的全屏。

Change the background color to black so that the bounds of the Collection View are perfectly visible.

将背景色更改为黑色,以使“收藏夹视图”的边界完全可见。

A UICollectionViewCell is visible at the top left of the CollectionView as seen in the image below.

如下图所示,UICollectionViewCell在CollectionView的左上方可见。

The UICollectionView cell is too small. Let’s make it bigger from the attributes inspector in the right panel. We’ve shown how to do it in the image below.

UICollectionView单元太小。 让我们通过右侧面板中的属性检查器将其放大。 我们已经在下图中显示了如何执行此操作。

We’ve defined the cell identifier too that would be used in the ViewController.swift file.

我们还定义了将在ViewController.swift文件中使用的单元格标识符。

As usual we need to control click and drag the Collection View to the dock ViewController button to connect the data source and the delegates. This can be done in the code too, but we prefer doing it here itself.

像往常一样,我们需要控制单击,并将“集合视图”拖动到停靠ViewController按钮上,以连接数据源和委托。 这也可以在代码中完成,但是我们更喜欢在这里进行。

The Storyboard is ready. We’ll add the collection view outlet to the ViewController.swift from the assistant editor as shown below.

情节提要已准备就绪。 我们将从助手编辑器将集合视图出口添加到ViewController.swift,如下所示。

The ViewController.swift is given below.

下面给出了ViewController.swift

import UIKit


let reuseIdentifier = "CellIdentifer";


class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //UICollectionViewDelegateFlowLayout methods
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat
    {
        
        return 4;
    }
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
    {
        
        return 1;
    }
    
    
    //UICollectionViewDatasource methods
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 100
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    
        cell.backgroundColor = self.randomColor()
        
        
        return cell
    }
    

    // custom function to generate a random UIColor
    func randomColor() -> UIColor{
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }


}

That’s a lot of code to digest at once! Let’s break it down.

一次要消化很多代码! 让我们分解一下。

We’ve added all the protocol methods used besides the UIViewController.

除了UIViewController之外,我们还添加了所有使用的协议方法。

Note: We’ve chosen UIViewController as the parent class and added a collection view in it. There’s a UICollectionViewController class too that can be used by replacing all instances of ViewController object (including the screen in the storyboards) with the UICollectionViewController.

注意:我们选择了UIViewController作为父类,并在其中添加了一个集合视图。 还有一个UICollectionViewController类,可以通过将UICollectionViewController对象的所有实例(包括情节提要中的屏幕)替换为UICollectionViewController来使用。

Now before we look into the UICollectionViewDelegateFlowLayout methods, once switch to the storyboard and focus the collection view and change the number of items to 2. An image like the one shown below would be seen.

现在,在我们研究UICollectionViewDelegateFlowLayout方法之前,一旦切换到情节UICollectionViewDelegateFlowLayout并聚焦集合视图并将项目数更改为2,便会看到如下图所示的图像。

We need to customise the spacing between the cells so that it looks more cleaner. Hence the two methods are implemented. The values returned are CGFloat values. After playing around with different values, we found the ones given above as the best fit for the present iOS app.

我们需要自定义单元格之间的间距,以使其看起来更干净。 因此,实现了两种方法。 返回的值是CGFloat值。 在尝试了不同的值之后,我们发现上面给出的值最适合当前的iOS应用。

The UICollectionViewDatasource methods are used to define the number of sections and the number of items. We’ve randomly assigned the numbers here.

UICollectionViewDatasource方法用于定义节数和项目数。 我们在这里随机分配了数字。

The function collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell is similar to the one in the TableView example. We’ve assigned a random background value to each cell using the randomColor() function by choosing a random R G B and returning the UIColor instance.

函数collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell与TableView示例中的collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell相似。 我们通过选择一个随机RGB并返回UIColor实例,使用randomColor()函数为每个单元分配了一个随机的背景值。

Running the application gives us the following output.

运行该应用程序将为我们提供以下输出。

This brings an end to iOS UICollectionView tutorial. You can download the iOS SimpleCollectionView app code from the link below.

这结束了iOS UICollectionView教程。 您可以从下面的链接下载iOS SimpleCollectionView应用程序代码。

Reference: Official Documenation

参考: 官方文件

翻译自: https://www.journaldev.com/10678/ios-uicollectionview-example-tutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值