開發環境
macOS Sierra 10.12、Xcode 8.0,如下圖所示:
總體思路
1、建立空白的storyboard用於呈現列表
2、實現自定義單個單元格(繼承自:UICollectionViewCell)
3、將列表(UICollectionView)注冊到頁面(StoryBoard)中,同時將單元格注冊到列表中
4、運行查看效果
1、建立StoryBoard
本項目集成了 Tab Bar 和 Navigation Bar,整個項目(main.storyboard)試圖如下所示:
這里在大廳頁面(HomeNavItem Scene)呈現列表,如下圖所示:
創建 HomeNavItemController.swift,作為上述頁面的后台代碼,關聯方式如上圖右上角 Custom Class 所示。
至此,界面端的工作就全部完畢了。
2、自定義單個單元格(HomeCollectionViewCell.swift),代碼如下所示:
import UIKit; class HomeCollectionViewCell: UICollectionViewCell { var title: UILabel?; // 單元格中的內容,如需其它控件,可自行添加 override init(frame: CGRect) { super.init(frame: frame); // 將 title 注冊到單元格 title = UILabel(frame: CGRect(x: 30, y: 0, width: UIScreen.main.bounds.width, height: 50)); title?.textColor = UIColor.black; self.addSubview(title!); self.backgroundColor = UIColor.blue; // 設置整個單元格背景顏色,測試單元格大小 } required init?(coder aDecoder: NSCoder) { fatalError("Cell 初始化失敗"); } }
3、將列表注冊到頁面中(HomeNavItemController.swift),同時,將單個單元格注冊到列表中,代碼如下所示:
1 import UIKit; 2 3 class HomeNavItemController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { 4 5 var colView: UICollectionView?; // 創建一個列表 6 7 // 加載界面 8 override func viewDidLoad() { 9 super.viewDidLoad(); 10 11 let layout = UICollectionViewFlowLayout(); 12 13 colView = UICollectionView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: self.view.bounds.height), collectionViewLayout: layout); 14 15 colView?.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: "colCell") 16 17 colView?.delegate = self; 18 colView?.dataSource = self; 19 colView?.backgroundColor = UIColor.white; 20 21 layout.itemSize = CGSize(width: 375, height: 300); 22 23 self.view.addSubview(colView!); 24 } 25 26 override func didReceiveMemoryWarning() { 27 super.didReceiveMemoryWarning(); 28 } 29 30 // Cell 數量 31 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 32 return 10; 33 } 34 35 // Cell 具體內容 36 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 37 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colCell", for: indexPath) as! HomeCollectionViewCell; 38 cell.title!.text = "這里是內容:\(indexPath.row)"; 39 return cell; 40 } 41 }
4、運行查看效果,如下圖所示:
最后,插一句,整個項目的結構圖如下所示:
特別說明:頁面中務必繼承UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout