Swift UICollectionView

UICollectionView是一種新的數(shù)據(jù)展示方式,簡(jiǎn)單來說可以把他理解成多列的UITableView(請(qǐng)一定注意這是UICollectionView的最最簡(jiǎn)單的形式)。

下面先通過一個(gè)簡(jiǎn)單的例子展示一下

 class SecondViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
     
    let screenWidth = UIScreen .mainScreen().bounds.width
    let screenHeight = UIScreen .mainScreen().bounds.height
    let idenContentString = "idenContentString"
    let headIdenString = "headIdenString"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.automaticallyAdjustsScrollViewInsets = true
        self .makeUICollectionView()
        
    }
    
    func makeUICollectionView()
    {
        //  設(shè)置 layOut
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical  //滾動(dòng)方向
        layout.itemSize = CGSizeMake((screenWidth - 30)/2, 80)
        // 設(shè)置CollectionView
        let ourCollectionView : UICollectionView = UICollectionView(frame: CGRectMake(0, 0, screenWidth, screenHeight), collectionViewLayout: layout)
        ourCollectionView.delegate = self
        ourCollectionView.dataSource = self
        ourCollectionView.backgroundColor = UIColor.whiteColor()
        ourCollectionView .registerClass(MyTestCollectionViewCell.self, forCellWithReuseIdentifier: idenContentString)
        
        self.view .addSubview(ourCollectionView)

    }
    
    //MARK: UICollectionViewDataSource
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 60
    }
    
    func  collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell  = collectionView.dequeueReusableCellWithReuseIdentifier(idenContentString, forIndexPath: indexPath) as! MyTestCollectionViewCell
        // 備注我們的小標(biāo)題
        let indexString = String(indexPath.row)
        cell.myLabel.text = "我的小標(biāo)題_" + indexString
        // 獲取隨機(jī)顏色
        let colorValue1 :CGFloat!  = CGFloat(CGFloat(random())/CGFloat(RAND_MAX))
        let colorValue2 :CGFloat!  = CGFloat(CGFloat(random())/CGFloat(RAND_MAX))
        let colorValue3 :CGFloat!  = CGFloat(CGFloat(random())/CGFloat(RAND_MAX))
        cell.myImageView.backgroundColor = UIColor(red: colorValue1, green: colorValue2, blue: colorValue3, alpha: 1.0)
        
        return cell;
        
    }
    //MARK:UICollectionViewDelegate
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("tap ==\(indexPath.row)")
    }
    
    //MARK:UICollectionViewDelegateFlowLayout
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
        return UIEdgeInsetsMake(5, 10, 5, 10)
    }
 }

在自定義的CollctionViewCell中

 class MyTestCollectionViewCell: UICollectionViewCell {

    override init(frame: CGRect) {
        
        super.init(frame: frame)
    
        // 由于測(cè)試,先不考慮 自動(dòng)布局 后期可以考慮 SnapKit
        self.myLabel.frame = CGRectMake(10, 60, frame.size.width - 20, 20)
        self.myImageView.frame = CGRectMake(10, 0, frame.size.width - 20, 60)
        
        self.contentView.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
        self.contentView .addSubview(self.myLabel)
        self.contentView .addSubview(self.myImageView)
  
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var myLabel:UILabel = {
    
        let label = UILabel()
        label.text = "我的小標(biāo)題"
        label.textAlignment = .Center
        label.font = UIFont.systemFontOfSize(12)
        return label
    
    }()
    
    var myImageView:UIImageView = {
        
        let imageView = UIImageView()
        imageView.backgroundColor = UIColor.lightGrayColor()
        return imageView
    
    }()
    
}
效果圖
UICollectionViewLayout

UICollectionViewLayout 是UICollectionView和UITableView最大的不同。UICollectionViewLayout可以說是UICollectionView的大腦和中樞,它負(fù)責(zé)了將各個(gè)cell、Supplementary View和Decoration Views進(jìn)行組織,為它們?cè)O(shè)定各自的屬性,包括但不限于:位置、尺寸、透明度、層級(jí)關(guān)系、形狀,等等。

  • itemSize 它定義了每一個(gè)item的大小。通過設(shè)定itemSize可以全局地改變所有cell的尺寸,如果想要對(duì)某個(gè)cell制定尺寸,可以使用- sizeForItemAtIndexPath indexPath:方法.

  • 間隔:可以指定item之間的間隔和每一行之間的間隔,和size類似,有全局屬性,也可以對(duì)每一個(gè)item和每一個(gè)section做出設(shè)定:

     public var minimumLineSpacing: CGFloat
     public var minimumInteritemSpacing: CGFloat
    
  • 滾動(dòng)方向:由屬性scrollDirection確定scroll view的方向,將影響Flow Layout的基本方向和由header及footer確定的section之間的寬度

    public enum UICollectionViewScrollDirection : Int {
    
            case Vertical
            case Horizontal
    }
    
  • Header和Footer尺寸: 同樣地分為全局和部分。需要注意根據(jù)滾動(dòng)方向不同,header和footer的高和寬中只有一個(gè)會(huì)起作用。垂直滾動(dòng)時(shí)section間寬度為該尺寸的高,而水平滾動(dòng)時(shí)為寬度起作用

      public var headerReferenceSize: CGSize
      public var footerReferenceSize: CGSize
      public var sectionInset: UIEdgeInsets
    

以及它的代理UICollectionViewDelegateFlowLayout

UICollectionViewCell

仔細(xì)一看它和UITableViewCell還是有很多區(qū)別的

public class UICollectionViewCell : UICollectionReusableView {

    public var contentView: UIView { get } 

    public var selected: Bool
    public var highlighted: Bool

    public var backgroundView: UIView?
    public var selectedBackgroundView: UIView?
}

首先注意它繼承的是UICollectionReusableView,和TableViewCell繼承UIView是不一樣的。

UICollectionReusableView
  • 狀態(tài)控制要比以前靈活一些,對(duì)應(yīng)的高亮和選中狀態(tài)分別由highlightedselected兩個(gè)屬性表示。
  • cell被選中時(shí)的背景更加靈活了,所有的cell中的子view,也包括contentView中的子view,在當(dāng)cell被選中時(shí),會(huì)自動(dòng)去查找view是否有被選中狀態(tài)下的改變。比如在contentView里加了一個(gè)normalselected指定了不同圖片的imageView,那么選中這個(gè)cell的同時(shí)這張圖片也會(huì)從normal變成selected,而不需要額外的任何代碼。
Header & Footer

也是先注冊(cè)

//注冊(cè)一個(gè)headView
 ourCollectionView .registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: headIdenString)

定義其大小和內(nèi)容

   //返回HeadView的寬高
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        
        return CGSize(width: ScreenWidth, height: 50)
    }
    
    //返回自定義HeadView或者FootView,我這里以headview為例
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
        var headView = UICollectionReusableView()
        if kind == UICollectionElementKindSectionHeader
        {
            headView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headIdenString, forIndexPath: indexPath)
            headView.backgroundColor = UIColor.redColor()

        }
        return headView
    }

效果圖如下,當(dāng)然那個(gè)numberOfSectionsInCollectionView進(jìn)行了改變

效果圖,section換了

記住headview也是繼承UICollectionReusableView的

總的來說,UICollectionView還有很多可以挖掘的功能,我們可以在API中充分發(fā)掘,它也會(huì)是我們后期常用的View,繼續(xù)加油····

備注參考

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionReusableView_class/index.html#//apple_ref/occ/instm/UICollectionReusableView/
http://www.onevcat.com/2012/08/advanced-collection-view/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容