ios 如何使用 Swift 创建一个简单的集合视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31735228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:04:33  来源:igfitidea点击:

How to make a simple collection view with Swift

iosswiftuicollectionview

提问by Suragch

I'm trying to learn how to use UICollectionView. The documentationis a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects.

我正在尝试学习如何使用UICollectionView. 该文件是一个有点难以理解和教程,我发现要么在Objective C或长期复杂的项目。

When I was learning how to use UITableView, We ? Swift'sHow to make a simple tableview with iOS 8 and Swifthad a very basic setup and explanation to get me going. Is there anything like this for UICollectionView?

当我在学习如何使用时UITableView我们?Swift 的How to make a simple tableview with iOS 8 and Swift有一个非常基本的设置和解释来让我开始。有这样的UICollectionView吗?

The answer below is my attempt to learn to do this.

下面的答案是我尝试学习做到这一点。

回答by Suragch

This project has been tested with Xcode 10 and Swift 4.2.

这个项目已经过 Xcode 10 和 Swift 4.2 的测试。

Create a new project

创建一个新项目

It can be just a Single View App.

它可以只是一个单一视图应用程序。

Add the code

添加代码

Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

创建一个新的 Cocoa Touch 类文件(文件 > 新建 > 文件... > iOS > Cocoa Touch 类)。命名它MyCollectionViewCell。这个类将保存您添加到故事板中单元格的视图的出口。

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myLabel: UILabel!
}

We will connect this outlet later.

我们稍后会连接这个插座。

Open ViewController.swift and make sure you have the following content:

打开 ViewController.swift 并确保您具有以下内容:

import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]


    // MARK: - UICollectionViewDataSource protocol

    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.myLabel.text = self.items[indexPath.item]
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

        return cell
    }

    // MARK: - UICollectionViewDelegate protocol

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

Notes

笔记

  • UICollectionViewDataSourceand UICollectionViewDelegateare the protocols that the collection view follows. You could also add the UICollectionViewFlowLayoutprotocol to change the size of the views programmatically, but it isn't necessary.
  • We are just putting simple strings in our grid, but you could certainly do images later.
  • UICollectionViewDataSourceUICollectionViewDelegate是集合视图遵循的协议。您还可以添加UICollectionViewFlowLayout协议以编程方式更改视图的大小,但这不是必需的。
  • 我们只是在我们的网格中放置简单的字符串,但您当然可以稍后再做图像。

Setup the storyboard

设置故事板

Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

将 Collection View 拖到 Storyboard 中的 View Controller。如果您愿意,您可以添加约束以使其填充父视图。

enter image description here

在此处输入图片说明

Make sure that your defaults in the Attribute Inspector are also

确保属性检查器中的默认值也是

  • Items: 1
  • Layout: Flow
  • 项目:1
  • 布局:流

The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

集合视图左上角的小框是一个集合视图单元格。我们将使用它作为我们的原型单元。将标签拖到单元格中并将其居中。如果您愿意,您可以调整单元格边框的大小并添加约束以将标签居中。

enter image description here

在此处输入图片说明

Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell"in ViewController.swift.

在集合视图单元格的属性检查器的标识符框中写入“单元格”(不带引号)。请注意,这与let reuseIdentifier = "cell"ViewController.swift 中的值相同。

enter image description here

在此处输入图片说明

And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

在单元格的身份检查器中,将类名设置为MyCollectionViewCell我们创建的自定义类。

enter image description here

在此处输入图片说明

Hook up the outlets

连接插座

  • Hook the Label in the collection cell to myLabelin the MyCollectionViewCellclass. (You can Control-drag.)
  • Hook the Collection View delegateand dataSourceto the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)
  • 胡克在收集电池的标签,以myLabelMyCollectionViewCell类。(您可以按住 Control 拖动。)
  • 将 Collection ViewdelegatedataSourceView Controller挂钩。(右键单击文档大纲中的集合视图。然后单击加号箭头并将其向上拖动到视图控制器。)

enter image description here

在此处输入图片说明

Finished

完成的

Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

这是添加约束以将 Label 置于单元格中的中心并将集合视图固定到父级的墙壁后的样子。

enter image description here

在此处输入图片说明

Making Improvements

改进

The example above works but it is rather ugly. Here are a few things you can play with:

上面的例子有效,但它相当丑陋。这里有一些你可以玩的东西:

Background color

背景颜色

In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.

在 Interface Builder 中,转到Collection View > Attributes Inspector > View > Background

Cell spacing

单元格间距

Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacingand make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

将单元格之间的最小间距更改为较小的值会使它看起来更好。在 Interface Builder 中,转到Collection View > Size Inspector > Min Spacing并减小值。“对于单元格”是水平距离,“对于线”是垂直距离。

Cell shape

细胞形状

If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyanin code above.

如果您想要圆角、边框等,您可以使用 cell layer。这是一些示例代码。你可以把它直接cell.backgroundColor = UIColor.cyan放在上面的代码之后。

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8

See this answerfor other things you can do with the layer (shadow, for example).

有关您可以对图层执行的其他操作(例如阴影),请参阅此答案

Changing the color when tapped

点击时更改颜色

It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewControllerclass:

当单元格对点击做出视觉响应时,它可以提供更好的用户体验。实现此目的的一种方法是在触摸单元格时更改背景颜色。为此,请将以下两个方法添加到您的ViewController类中:

// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.red
}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.cyan
}

Here is the updated look:

这是更新后的外观:

enter image description here

在此处输入图片说明

Further study

进一步研究

UITableView version of this Q&A

本问答的 UITableView 版本

回答by Saranjith

Delegates and Datasources of UICollectionView

UICollectionView 的委托和数据源

//MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
    configureCell(cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.blackColor()


    //Customise your cell

}

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      // When user selects the cell
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
     // When user deselects the cell
}

回答by Abhishek Mishra

For swift 4.2--

对于swift 4.2——

//MARK: UICollectionViewDataSource

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    configureCell(cell: cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.black


    //Customise your cell

}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // When user selects the cell
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // When user deselects the cell
}

回答by Aditya Sharma

UICollectionView implementation is quite interesting. You can use the simple source code and watch a video tutorial using these links :

UICollectionView 的实现非常有趣。您可以使用简单的源代码并使用以下链接观看视频教程:

https://github.com/Ady901/Demo02CollectionView.git

https://github.com/Ady901/Demo02CollectionView.git

https://www.youtube.com/watch?v=5SrgvZF67Yw

https://www.youtube.com/watch?v=5SrgvZF67Yw

extension ViewController : UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
        cell.titleLabel.text = nameArr[indexPath.row]
        cell.userImageView.backgroundColor = .blue
        return cell
    }

}

extension ViewController : UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }

}

回答by Dilraj Singh

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a linkfrom where you will get everything in simple steps.

UICollectionView 与 UITableView 相同,但它为我们提供了简单创建网格视图的附加功能,这在 UITableView 中有点问题。这将是一篇很长的文章,我提到了一个链接,您可以通过简单的步骤获得所有内容。