快速开始uicollectionview

总览 (Overview)

In iOS, a CollectionView is a flexible way to show user ordered data. Like Tableview, it has a different method to present data in a grid or customizable layout. In this tutorial, we will learn how to configure a basic CollectionView in iOS using default and custom cell. So let’s get started

在iOS中,CollectionView是一种显示用户订购数据的灵活方式。 与Tableview一样,它具有以网格或可自定义布局显示数据的不同方法。 在本教程中,我们将学习如何使用默认和自定义单元在iOS中配置基本的CollectionView。 所以我们开始吧

This tutorial is written using Swift 5, Xcode 11.2, iOS 13 & Storyboard Interface.

本教程使用Swift 5,Xcode 11.2,iOS 13和Storyboard Interface编写

  1. Configure CollectionView using default cell: Let’s see how we can configure a CollectionView using the default cell step by step.

    使用默认单元格配置CollectionView:让我们逐步了解如何使用默认单元格配置CollectionView。

Step 1: Create an Xcode project & setup CollectionView: Open your Xcode -> create a new Xcode project -> Choose ios and single view application as your project template -> name it as you want -> create. After that, your file structure should seem like this.

步骤1创建一个Xcode项目并设置CollectionView :打开Xcode->创建一个新的Xcode项目->选择ios和single view应用程序作为项目模板->根据需要命名->创建。 之后,您的文件结构应如下所示。

Image for post

Open your “Main.storyboard” file, you will find a view controller there. Drag and drop a CollectionView from the object library. Set constrain as (0,0,0,0) as following

打开“ Main.storyboard”文件,您将在其中找到一个视图控制器。 从对象库中拖放一个CollectionView。 设置约束为(0,0,0,0)如下

Image for post

Now open your “ViewController.swift” file from the project navigator by “Option + click” on that. Insert outlate of your CollectionView to the view controller file.

现在,通过在项目导航器中单击“ Option +单击”打开“ ViewController.swift”文件。 将CollectionView的外部插入到视图控制器文件中。

Image for post

Extends your “ViewController” class to “UICollectionViewDelegate” and “UICollectionViewDataSource”. You have to add some protocol stubs, add them. You “ViewController” should seem like this

将“ ViewController”类扩展为“ UICollectionViewDelegate”和“ UICollectionViewDataSource”。 您必须添加一些协议存根,然后将其添加。 您的“ ViewController”应该看起来像这样

Image for post

Now set delegate and data source for your CollectionView. You can do it by writing two lines of code into your “viewDidLoad” method. In my case those are

现在为您的CollectionView设置委托和数据源。 您可以通过在“ viewDidLoad”方法中编写两行代码来实现。 以我为例

demoCollectionView.delegate = selfdemoCollectionView.dataSource = self

or you can set it using the storyboard like this

或者您可以像这样使用情节提要进行设置

Image for post

That’s it. Your CollectionView is configured and set to show data.

而已。 您的CollectionView已配置并设置为显示数据。

Step 2: Setup CollectionView cell: When you add a CollectionView to your view controller from the object library you should notice that by default a cell is also added to that collection view. We will create a new Cocoa Touch file subclassing “UICollectionViewCell” for that CollectionView cell. Select the CollectionView cell from the storyboard, set the Custom class and identifier for the cell.

步骤2:设置CollectionView单元格 :从对象库中将CollectionView添加到视图控制器时,您应该注意到,默认情况下,一个单元格也被添加到该集合视图中。 我们将为该CollectionView单元创建一个新的Cocoa Touch文件,其子类为“ UICollectionViewCell”。 从情节提要中选择CollectionView单元,设置该单元的“自定义”类和标识符。

Image for post

If you complete until this your CollcetionView cell is also configured for showing data.

如果您在此之前完成操作,则还将CollcetionView单元配置为显示数据。

Step 3: Show data: Now we will show data using CollectionView and its cell. Before that, we will take a label into our CollectionView cell. Put the label central horizontally and vertically in the cell. Take an outlet for that label to cell class and change cell background color as you want to visualize the cell.

步骤3:显示数据:现在,我们将使用CollectionView及其单元显示数据。 在此之前,我们将一个标签放入CollectionView单元中。 将标签水平和垂直放置在单元格的中央。 为该标签选择一个出口以使其分类,并根据需要更改单元格背景色以使其形象化。

Image for post

Edit your “numberOfRowsInSection” method as following. This method actually returns the number of rows that CollectionView has. In my case, I want to show 25 static cells.

如下编辑“ numberOfRowsInSection”方法。 此方法实际上返回CollectionView具有的行数。 就我而言,我想显示25个静态单元格。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 25}

Configure your “cellForRowAt” function as following. This method will configure your every cell of the CollectionView using the class and identifier of the cell. We set the label text that we previously took with the corresponding cell number for every cell.

如下配置“ cellForRowAt”函数。 此方法将使用单元格的类和标识符配置CollectionView的每个单元格。 我们为每个单元格设置了以前使用的标签文本以及相应的单元格编号。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCollectionViewCell", for: indexPath) as! DemoCollectionViewCellcell.textLbl.text = "\(indexPath.row)"return cell}

Complete code snippet of your “ViewController” class should something like this.

您的“ ViewController”类的完整代码段应如下所示。

import UIKitclass ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {@IBOutlet weak var demoCollectionView: UICollectionView!override func viewDidLoad() {super.viewDidLoad()demoCollectionView.delegate = selfdemoCollectionView.dataSource = self}func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 25}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCollectionViewCell", for: indexPath) as! DemoCollectionViewCellcell.textLbl.text = "\(indexPath.row)"return cell}}

Build and Run the project on your simulator. You will see something like this.

在模拟器上生成并运行项目。 您将看到类似这样的内容。

Image for post

2. Configure CollectionView using custom cell: We can also create a cell using a XIB file and configure it with CollectionView. Let’s see how can we make it.

2. 使用自定义单元配置CollectionView:我们还可以使用XIB文件创建单元,并使用CollectionView对其进行配置。 让我们看看如何做到这一点。

Step 1: Create an Xcode project & setup CollectionView: We will use the same project and CollectionView in this tutorial. You can make a different project and CollectionView as I describe above.

步骤1创建一个Xcode项目并设置CollectionView :在本教程中,我们将使用相同的项目和CollectionView。 您可以按照我上面的描述创建其他项目和CollectionView。

Step 2: Setup CollectionView cell: Create a new Cocoa Touch file. Create a class subclassing “UICollectionViewCell”. Please make sure you are tick mark on the “also create XIB file” box. Set an identifier for the cell.

步骤2:设置CollectionView单元 :创建一个新的Cocoa Touch文件。 创建一个子类为“ UICollectionViewCell”的类。 请确保在“同时创建XIB文件”框中打勾 。 设置单元格的标识符。

Image for post

Now into your custom cell drag and drop a view from the object library and pin it as (0,0,0,0) with safe area.

现在,将其从对象库中拖放到自定义单元中,并将其固定为(0,0,0,0)并带有安全区域。

Drag and drop a label into that view and set constrain for the label as central horizontally and vertically in the center. Take an outlet of this label to its cell class as textLbl. Change the background color of your view. Sounds familiar? Yes, we follow those similar steps to configure our default cell.

将标签拖放到该视图中,并将标签的约束设置为水平居中,垂直居中。 将此标签的出口作为textLbl移至其单元格类。 更改视图的背景色。 听起来很熟悉? 是的,我们按照这些类似的步骤来配置我们的默认单元格。

We are using a XIB file as the cell for our CollectionView that’s why we have to register cell with our CollectionView. We can register the cell using its name and identifier. Write this into the “viewDidLoad()” of your “ViewController” class.

我们将XIB文件用作CollectionView的单元格,这就是为什么我们必须向CollectionView注册单元格的原因。 我们可以使用其名称和标识符来注册该单元格。 将此写入“ ViewController”类的“ viewDidLoad()”。

demoCollectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")

Change your CollectionView delegate and data source method as follow to show data using the custom cell.

如下更改您的CollectionView委托和数据源方法,以使用自定义单元格显示数据。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 25}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionViewCell", for: indexPath) as! CustomCollectionViewCellcell.textLbl.text = "\(indexPath.row)"return cell}

Complete code snippet of your “ViewController” class should something like this.

您的“ ViewController”类的完整代码段应如下所示。

import UIKitclass ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {@IBOutlet weak var demoCollectionView: UICollectionView!override func viewDidLoad() {super.viewDidLoad()demoCollectionView.delegate = selfdemoCollectionView.dataSource = selfdemoCollectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")}func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 25}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionViewCell", for: indexPath) as! CustomCollectionViewCellcell.textLbl.text = "\(indexPath.row)"return cell}}

Build and Run again, you will see the data is loaded into your CollectionView using a custom XIB cell.

再次构建并运行,您将看到使用自定义XIB单元将数据加载到CollectionView中。

Image for post

Congratulation 🎉 🎉 🎉 Now you know how to configure a CollectionView with a default and custom cell. You can do a lot of cool stuff using different kinds of CollectionView methods. Please check the Apple documentation for further clarification.

恭喜您,现在您知道如何使用默认和自定义单元配置CollectionView。 您可以使用各种CollectionView方法来做很多很酷的事情。 请检查Apple文档以获得进一步的说明。

If you found this article useful please share and give some clap 👏👏👏Check my other articles on Medium and connect me on LinkedIn.

如果您觉得这篇文章很有用,请分享并给予一些鼓掌 。👏👏👏查看我在Medium上的其他文章,并在LinkedIn上与我联系。

Thank you for reading & Happy coding 🙂

感谢您的阅读和快乐的编码🙂

翻译自: https://levelup.gitconnected.com/getting-started-with-uicollectionview-in-swift-a1a1ee56e47a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值