Swift UICollectionView

2,314 阅读2分钟

UICollectionVIew

以网格的方式去展示照片等内容,类似iPhone展示照片,大众点评或者小红书的分享页面

程序的最终展示结果如下

程序的最终展示结果如下

分为上下两组,在程序中定义的Section 在每一组Section中,有上面的UILabel Header和下面的UI Label Footer。在每个Section中,定义每个存储图片的单元格为一个cell。

建立ViewController,并且在viewDidLoad()中设置底色。

 var fullScreenSize :CGSize! = UIScreen.main.bounds.size
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置底色
        self.view.backgroundColor = UIColor.white
        

区别于UITableView, UICollectionView需要设置UICollectionViewFlowLayout(),用来定义呈现的样式。

Quick Hlep中的介绍

viewDidLoad()里建立 UICollectionViewFlowLayout :

 // 建立 UICollectionViewFlowLayout
        let layout = UICollectionViewFlowLayout()

对Section的设置

    // 設置 section 的間距 四個數值分別代表 上、左、下、右 的間距
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        
        // 設置每一行的間距
        layout.minimumLineSpacing = 5

设置Section中用来展示照片的cell的尺寸

 layout.itemSize = CGSize(width:
 CGFloat(fullScreenSize.width)/3 - 10.0, height:
 CGFloat(fullScreenSize.width)/3 - 10.0)

对cell的注册

myCollectionView.register(MyCollectionViewCell.self,
forCellWithReuseIdentifier: "Cell")

对header 及 footer 的设置以及注册

layout.headerReferenceSize = CGSize(width:
  fullScreenSize.width, height: 40)
layout.footerReferenceSize = CGSize(width:
  fullScreenSize.width, height: 40)
  // 注册 section 的 header 跟 footer 以供后续重复使用
 myCollectionView.register(UICollectionReusableView.
        self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
        withReuseIdentifier: "Header")
myCollectionView.register(UICollectionReusableView.
     self, forSupplementaryViewOfKind:
     UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer")

建立UICollectionView

 let myCollectionView = UICollectionView(frame: CGRect(x: 0,
    y: 20, width: fullScreenSize.width, height:
   fullScreenSize.height - 20), collectionViewLayout: layout)

设置委任对象

 myCollectionView.delegate = self
 myCollectionView.dataSource = self

加入页面中

 self.view.addSubview(myCollectionView)

建立新的文件页面,定义UICollectionViewCell的类别

在新的文件页面中,加入需要的元素,一张图片 UIImageView 及图片序号 UILabel :

var imageView:UIImageView!
var titleLabel:UILabel!

在override init中

 override init(frame: CGRect) {
        super.init(frame: frame)

        // 取得屏幕宽度
        let w = Double(UIScreen.main.bounds.size.width)
        
        // 建立一个 UIImageView
        imageView = UIImageView(frame: CGRect(x: 0, y: 0,
        width: w/3 - 10.0, height: w/3 - 10.0))
        self.addSubview(imageView)
        
        // 建立一個 UILabel
        titleLabel = UILabel(frame:CGRect(x: 0, y: 0, 
        width: w/3 - 10.0, height: 40))
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor.orange
        self.addSubview(titleLabel)
    }
    

委任模式中

回到ViewController,先加上委任需要的协定

class ViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource {

定义一组中有几个cell

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

和cell中要展示的内容

 func collectionView(_ collectionView: UICollectionView,
 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 依据前面注册设置的识别名称 "Cell" 
    let cell = collectionView.dequeueReusableCell
(withReuseIdentifier:"Cell", for: indexPath) 
as! MyCollectionViewCell
        
    // 设置 cell 內容 (即自定义元件里 增加的图片与文字元件)
    cell.imageView.image = UIImage(named: "0\(indexPath.item + 1).jpg")   //
    cell.titleLabel.text = "0\(indexPath.item + 1)"
    return cell
    }

定义有几个Section

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

点开cell后执行的动作

  func collectionView(_ collectionView: UICollectionView,
  didSelectItemAt indexPath: IndexPath) {
        print("你選擇了第 \(indexPath.section + 1) 組的")
        print("第 \(indexPath.item + 1) 張圖片")
    }

设置重复使用的header 或 footer

func collectionView(collectionView: UICollectionView, 
    viewForSupplementaryElementOfKind kind: String,
    atIndexPath indexPath: NSIndexPath) 
    -> UICollectionReusableView {
    // 建立 UICollectionReusableView
    var reusableView = UICollectionReusableView()

    // 顯示文字
    let label = UILabel(frame: CGRect(
      x: 0, y: 0, 
      width: fullScreenSize.width, height: 40))
    label.textAlignment = .Center

    // header
    if kind == UICollectionElementKindSectionHeader {
// 依据前面注册设置的识别名称 "Header" 取得目前使用的 header
        reusableView = 
collectionView.dequeueReusableSupplementaryViewOfKind(
        UICollectionElementKindSectionHeader, 
        withReuseIdentifier: "Header",
        forIndexPath: indexPath)
        // 设置 header 的內容
        reusableView.backgroundColor = 
          UIColor.darkGrayColor()
        label.text = "Header";
        label.textColor = UIColor.whiteColor()

    } else if kind ==
    UICollectionElementKindSectionFooter {
// 依据前面注册设置的识别名称 "Footer" 取得目前使用的 footer
        reusableView = 
collectionView.dequeueReusableSupplementaryViewOfKind(
        UICollectionElementKindSectionFooter,
        withReuseIdentifier: "Footer",
        forIndexPath: indexPath)
        // 设置 footer 的內容
        reusableView.backgroundColor =
          UIColor.cyanColor()
        label.text = "Footer";
        label.textColor = UIColor.blackColor()

    }

    reusableView.addSubview(label)
    return reusableView
}