如何使用Swift创建一个简单的集合视图 [英] How to make a simple collection view with Swift

查看:103
本文介绍了如何使用Swift创建一个简单的集合视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用 UICollectionView



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




  • 项目:1

  • 布局:流程



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





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





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





连接插座




  • 将收集单元格中的标签挂钩到 myLabel MyCollectionViewCell 类。 (您可以



    已完成



    这是在向中心添加约束后的样子单元格中的Label并将Collection View固定到父级的墙上。





    进行改进



    以上示例有效,但相当丑陋。以下是您可以使用的一些内容:



    背景颜色



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



    单元格间距



    将单元格之间的最小间距更改为较小的值会使它看起来更好。在界面生成器中,转到集合视图>尺寸检查器>最小间距并使值更小。 For cells是水平距离,For lines是垂直距离。



    单元格形状



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

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

    有关您可以执行的其他操作,请参阅



    进一步研究





    此Q& A的UITableView版本




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

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

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

    解决方案

    This project has been tested with Xcode 9 and Swift 4.

    Create a new project

    It can be just a Single View Application.

    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.

    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:

    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

    • UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol 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.

    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.

    Make sure that your defaults in the Attribute Inspector are also

    • Items: 1
    • Layout: Flow

    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.

    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.

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

    Hook up the outlets

    • Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
    • Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

    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.

    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.

    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 Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

    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.cyan in code above.

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

    See this answer for 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 ViewController class:

    // 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:

    Further study

    UITableView version of this Q&A

    这篇关于如何使用Swift创建一个简单的集合视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆