iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 6
2
Software Development

Swift零基礎實作旅遊景點app系列 第 6

Swift從零開始-Day6:UICollectionView基礎學習

分類:UIKit學習

1. UICollectionView特色

  • 將CollectionView拉進storyboard時可以看到主要分成兩個部分,包括Cell與Layout(為UICollectionViewFlowLayout類別)。
  • Cell處理方式與TableView類似,而Layout是負責設定cell的相關排版。
  • Layout相關設定:
  1. sectionInset:處理Section的間距,UIEdgeInsetsMake(5, 20, 5, 20)四個數值分別代表上、左、下、右。
  2. itemSize:處理Cell的尺寸。
  3. 如果有header或footer,headerReferenceSize 及footerferenceSize

2. UICollectionView實作

  • 將CollectionView拉進storyboard。再將CollectionView及Layout與程式碼連結。

  • 在ViewDidLoad中進行Layout的設定,也可以選右邊的屬性版來達到一樣的效果。

  • 進行Cell的設定,包含identifier、cell內容實作等:先新增一個ImageView到CollectionView的cell中,並新增一個MyCustomCollectionViewCell的檔案。

  • 最後類似於TableViewCell的設定,程式碼如下:
 func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sceneArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCustomCollectionViewCell
        
        cell.myCellImageView.image = UIImage(named: sceneArray[indexPath.row])
        
        return cell
    }
    

PS: 為了畫面上的美觀.重新設定Layout

 myCollectionViewLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 20)
        myCollectionViewLayout.itemSize = CGSize(width: fullScreenSize.width/2-20, height: 200) //設定cell的size
        myCollectionViewLayout.minimumLineSpacing = 5 //設定cell與cell間的縱距

執行結果如下圖:

小結:UICollectionView在建立上與UITableView相當類似,較不同的地方是在於CollectionView如果要建立header及footer必須使用Collection Reusable View,並實作以下方法。

func collectionView(_ collectionView: UICollectionView,
                        viewForSupplementaryElementOfKind kind: String,
                        at indexPath: IndexPath) -> UICollectionReusableView 

上一篇
Swift從零開始-Day5:UITableView基礎學習
下一篇
Swift從零開始-Day7:UIScrollView基礎學習(含UIPageControl基礎學習)
系列文
Swift零基礎實作旅遊景點app30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言