鐵人賽還有最後10天!!
這次我們用 collection View 來練習
預計要做一個 相片簿,其中每航有三張,每組有七張
在 < ViewController.swift > 中
3. 與 tableview 一樣要繼承其他兩個子類別並且取得螢幕大小
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
var fullScreenSize : CGSize!
在 < viewDidLoad() > 中
4. * 取得螢幕大小
* 設定背景顏色、section間距、每一行的距離
* 設定 layout 為 FlowLayout
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// get the screen size
fullScreenSize = UIScreen.main.bounds.size
//set up the background color
self.view.backgroundColor = UIColor.white
//set up the UICollectionViewFlowLayout
let layout = UICollectionViewFlowLayout()
UICollectionViewFlowLayout
**//set up the section
layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
//set up the spacing of each line
layout.minimumLineSpacing = 5
//set up the size of each cell
layout.itemSize = CGSize(width:CGFloat(fullScreenSize.width)/3 - 10.0, height:CGFloat(fullScreenSize.height)/3 - 10.0)
//set up the collectionView
// init = UICollectionView(frame:CGRect, collectionViewLayout:UICollectionViewLayout)
let myCollectionView = UICollectionView(frame:CGRect(x:0, y:20, width:fullScreenSize.width, height:fullScreenSize.height-20), collectionViewLayout:layout)
//register the Cell for reuse
myCollectionView.register(
MyCollectionViewCell.self,
forCellWithReuseIdentifier: "Cell")
// setup the delegate and datasource
myCollectionView.delegate = self
myCollectionView.dataSource = self
// add the cell into collectionView
self.view.addSubview(myCollectionView)
在 < MyCollectionViewCell > 中
8. 先宣告一個 imageview和一個 titlelabel
class MyCollectionViewCell: UICollectionViewCell{
var imageView:UIImageView!
var titleLabel:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
let w = Double(UIScreen.main.bounds.size.width)
//create a imageview
imageView = UIImageView(frame: CGRect(x: 0, y: 0,width: w/3 - 10.0, height: w/3 - 10.0))
self.addSubview(imageView)
//create a label
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)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
在 < ViewController > 中
11. 設定每個cell的內容,並且把 imageview和 title label 內容丟進來
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)
as! MyCollectionViewCell
// setup the Label and image into the imageview
cell.imageView.image = UIImage(named: "0\(indexPath.item + 1).jpg")
cell.titleLabel.text = "0\(indexPath.item + 1)"
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
// number of section
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
結果是成功了,可是排版跟原本的設定有落差,明天再繼續!!!