我正在努力学习如何使用UICollectionView.documentation有点难理解,我发现的教程要么是在Objective C中,要么是在长期复杂的项目中.

当我在学习如何使用UITableView,We ❤ Swift'sHow to make a simple tableview with iOS 8 and Swift的时候,有一个非常基本的设置和说明让我开始使用.UICollectionView号有类似的东西吗?

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

推荐答案

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

Create a new project

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

Add the code

创建新的Cocoa Touch类文件(文件&>;新建&>文件.>;iOS>;可可touch 类).把它命名为MyCollectionViewCell.这个类将为您添加到故事板中的单元格的视图保留插座.

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var myLabel: UILabel!
}

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

打开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.row] // The row value is the same as the index of the desired text within the array.
        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

  • UICollectionViewDataSourceUICollectionViewDelegate是集合视图遵循的协议.您还可以添加UICollectionViewFlowLayout协议以编程方式更改视图的大小,但这不是必需的.
  • 我们只是把简单的字符串放在网格中,但你当然可以稍后再做图片.

Set up the storyboard

将集合视图拖动到情节提要中的视图控制器.如果愿意,可以添加约束以使其填充父视图.

enter image description here

确保属性判断器中的默认值也为

  • 品目:1
  • 布局:流量

集合视图左上角的小方框是集合视图单元格.我们将把它作为我们的原型细胞.将标签拖到单元格中并居中.如果愿意,可以调整单元格边界的大小并添加约束以使标签居中.

enter image description here

在集合视图单元格的Attributes Inspector的Identifier框中写入"cell"(不带引号).请注意,该值与ViewController.swft中的let reuseIdentifier = "cell"值相同.

enter image description here

在单元格的Identity Inspector中,将类名设置为MyCollectionViewCell,这是我们创建的自定义类.

enter image description here

Hook up the outlets

  • 将集合单元格中的标签挂接到MyCollectionViewCell类中的myLabel.(你可以 Select Control-drag.)
  • 将集合视图delegatedataSource挂接到视图控制器.(在文档大纲中的集合视图上单击鼠标右键.然后单击并向上拖动加号箭头到视图控制器.)

enter image description here

Finished

以下是添加约束以使标签在单元格中居中,并将集合视图固定到父视图的墙后的情况.

enter image description here

Making Improvements

上面的例子很好用,但相当难看.这里有几个你可以玩的东西:

Background color

在界面生成器中,转到Collection View > Attributes Inspector > View > Background.

Cell spacing

将单元格之间的最小间距更改为较小的值会使其看起来更好.在界面生成器中,转到您的Collection View > Size Inspector > Min Spacing并将值设置得更小."对于单元格"是水平距离,"对于线条"是垂直距离.

Cell shape

如果你想要圆角、边框等等,你可以在layer号电池上玩.下面是一些示例代码.在上面的代码中,你可以把它直接放在cell.backgroundColor = UIColor.cyan后面.

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

请参见this answer,了解您可以对该层执行的其他操作(例如阴影).

Changing the color when tapped

当细胞对轻击做出视觉响应时,它会带来更好的用户体验.实现这一点的一种方法是在touch 单元格时更改背景 colored颜色 .为此,请将以下两个方法添加到您的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

Ios相关问答推荐

如何在Flutter 中为S家长增加一个相对高度的间距

更改文本在Flutter 中的位置

通过拖动更改视图位置的SwiftUI会引发UI错误

使用AVCaptureEventInteraction捕获音量按键快门

Swift导航远离视频导致崩溃

在相机动作之前快速防止场景视点重置

Xcode 15模拟器用x86_64编译

Swift - 缺少函数参数在编译期间不会失败,甚至会导致不同的数据类型?

如何在Swift/Combine中从timer.publish属性传递两个参数到任意方法

_SKStoreProductParameterAdNetworkSourceIdentifier未定义符号

垂直分页 UIScrollView 高度不正确

Flutter 构建 ios 失败:运行 pod 安装时出错

iOS按钮和navigationLink在List中相邻

在 SwiftUI 中将 TextEditor 文本计数连接到 ProgressView

JSONDecoder 在模拟器上运行良好时无法在真实设备上解码

如何识别 SwiftUI 中点击的按钮 ID 以使该按钮动画化?

每次运行后,Xcode 6 都会在 iOS8 模拟器中重命名我的应用程序目录.

如何在 UIActivityViewController 中设置邮件主题?

无论我将构建版本或应用程序版本更改为什么,都会出现 ITEMS-4238冗余二进制上传错误

如何识别导航堆栈中的前一个视图控制器