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

Sur*_*gch 171 ios uicollectionview swift

我正在努力学习如何使用UICollectionView.该文件是一个有点难以理解,而我发现教程无论是在目标C或长期复杂的项目当中.

当我学习如何使用时UITableView,我们❤Swift的 如何用iOS 8和Swift制作一个简单的桌面视图有一个非常基本的设置和解释让我去.有这样的东西UICollectionView吗?

下面的答案是我试图学习如何做到这一点.

Sur*_*gch 476

该项目已经过Xcode 10和Swift 4.2的测试.

创建一个新项目

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

添加代码

创建一个新的Cocoa Touch类文件(文件>新建>文件...> iOS> Cocoa Touch类).说出来MyCollectionViewCell.此类将保留您在故事板中添加到单元格的视图的出口.

import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myLabel: UILabel!
}
Run Code Online (Sandbox Code Playgroud)

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

打开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)!")
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记

  • UICollectionViewDataSource并且UICollectionViewDelegate是集合视图遵循的协议.您还可以添加UICollectionViewFlowLayout协议以编程方式更改视图的大小,但这不是必需的.
  • 我们只是在网格中添加简单的字符串,但您可以在以后执行图像.

设置故事板

将集合视图拖到故事板中的视图控制器.您可以添加约束以使其填充父视图(如果您愿意).

在此输入图像描述

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

  • 项目:1
  • 布局:流程

Collection View左上角的小方框是Collection View Cell.我们将它用作我们的原型单元.将标签拖到单元格中并使其居中.您可以调整单元格边框的大小,并根据需要添加约束以使Label居中.

在此输入图像描述

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

在此输入图像描述

在单元格的Identity Inspector中,将类名设置为MyCollectionViewCell我们制作的自定义类.

在此输入图像描述

连接插座

  • 胡克在收集电池的标签,以myLabelMyCollectionViewCell类.(你可以控制 - 拖动.)
  • 将集合视图delegatedataSource视图控制器挂钩.(右键单击"文档大纲"中的"集合视图".然后单击并将加号向下拖动到视图控制器.)

在此输入图像描述

成品

这是在添加约束以使Label在单元格中居中并将Collection View固定到父级墙壁之后的样子.

在此输入图像描述

改进

上面的例子有效,但它相当丑陋.以下是您可以使用的一些内容:

背景颜色

在Interface Builder中,转到" 集合视图">"属性"检查器>"视图">"背景".

细胞间距

将单元格之间的最小间距更改为更小的值使其看起来更好.在Interface Builder中,转到" 集合视图">"大小检查器">"最小间距",并使值更小."对于单元格"是水平距离,"对于线"是垂直距离.

细胞形状

如果你想要圆角,边框等,你可以玩单元格layer.这是一些示例代码.您可以将其直接cell.backgroundColor = UIColor.cyan放在上面的代码中.

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
Run Code Online (Sandbox Code Playgroud)

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

轻敲时更改颜色

当细胞在视觉上对水龙头作出反应时,它可以提供更好的用户体验.实现此目的的一种方法是在触摸单元格时更改背景颜色.为此,请将以下两种方法添加到您的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
}
Run Code Online (Sandbox Code Playgroud)

这是更新的外观:

在此输入图像描述

进一步研究

这个Q&A的UITableView版本

  • 我希望Apple的文档与此解释一样容易阅读 (35认同)
  • 如果您没有通过控制 - 从故事板中的标签拖动到代码中的`@Label`的@ IBOutlet`来连接插座,那么您将会遇到这样的崩溃. (4认同)
  • 如果您正在使用接口构建器并使用插座引用单元,请不要在控制器中注册自定义单元类.见[this](http://stackoverflow.com/questions/35239543/nil-label-for-custom-uicollectioncell) (3认同)
  • 如果 UICollectionViewCell 出口为零,那么您必须删除`self.collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")`。如果您仍然有问题,请检查“dequeueReusableCellWithReuseIdentifier”和故事板中的“reuseIdentifier”是否相同 (2认同)

Abh*_*hra 5

对于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
}
Run Code Online (Sandbox Code Playgroud)