如何使用 Swift 制作简单的集合视图

发布于 2022-07-28 22:57:59

我正在尝试学习如何使用UICollectionView.
文档有点难以理解,我发现的教程要么是在
Objective C 中,要么是在很长的复杂项目中。

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

下面的答案是我尝试学习这样做。

关注者
0
被浏览
16
1 个回答
  • 面试哥
    面试哥 2022-07-28
    为面试而生,有面试问题,就找面试哥。

    该项目已使用 Xcode 10 和 Swift 4.2 进行了测试。

    创建一个新项目

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

    添加代码

    创建一个新的 Cocoa Touch Class 文件(File > New > File… > iOS > Cocoa Touch
    Class)。命名它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)!")
        }
    }
    

    笔记

    • UICollectionViewDataSource并且UICollectionViewDelegate是集合视图遵循的协议。您还可以添加UICollectionViewFlowLayout协议以编程方式更改视图的大小,但这不是必需的。
    • 我们只是将简单的字符串放入我们的网格中,但您当然可以稍后再制作图像。

    设置故事板

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

    mISk8.png

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

    • 项目:1
    • 布局:流

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

    veuvJ.png

    在 Collection View Cell 的 Attributes Inspector 的 Identifier
    框中写入“cell”(不带引号)。请注意,这与 ViewController.swift 中的值相同let reuseIdentifier = "cell"

    wBzIp_2.png

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

    lP6gC_3.png

    连接插座

    • 将集合单元格中的标签挂接到myLabel类中MyCollectionViewCell。(您可以按住 Control 并拖动。)
    • 将 Collection ViewdelegatedataSourceView Controller 挂钩。(右键单击文档大纲中的集合视图。然后单击并向上拖动加号箭头到视图控制器。)

    go3aZ_4.png

    完成的

    这是在添加约束以使单元格中的标签居中并将集合视图固定到父项的墙壁后的样子。

    i6F79_5.png

    进行改进

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

    背景颜色

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

    单元间距

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

    细胞形状

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

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

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

    在 swift 4 中快速测试的东西

    import UIKit
    
    extension UIView {
        @IBInspectable var dropShadow: Bool {
            set{
                if newValue {
                    layer.shadowColor = UIColor.black.cgColor
                    layer.shadowOpacity = 0.4
                    layer.shadowRadius = 1
                    layer.shadowOffset = CGSize.zero
                } else {
                    layer.shadowColor = UIColor.clear.cgColor
                    layer.shadowOpacity = 0
                    layer.shadowRadius = 0
                    layer.shadowOffset = CGSize.zero
                }
            }
            get {
                return layer.shadowOpacity > 0
            }
        }
    }
    

    生产

    x8AYT_6.jpg

    如果您像这样在检查器中启用它:

    sgIPi_7.png

    它将添加用户定义的运行时属性,从而导致:

    0nslM_8.png

    (我之前添加了cornerRadius = 8

    点击时更改颜色

    当单元格对点击做出视觉响应时,它可以提供更好的用户体验。实现此目的的一种方法是在触摸单元格时更改背景颜色。为此,请将以下两种方法添加到您的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
    }
    

    这是更新后的外观:

    C38GW_9.png

    进一步研究



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看