【iOS】UICollectionView

学习文章

使用UICollectionView

一 初步UICollectionView

使用UICollectionView的流程:
  1. 设定一个UICollectionViewFlowLayout

  2. 使用这个设定的UICollectionViewFlowLayout来初始化UICollectionView

  3. 设置代理对象

  4. 继承UICollectionViewCell设定重用的cell

效果
【iOS】UICollectionView_第1张图片
�初步效果.png
源码:

LargeUICollectionViewFlowLayout

import UIKit

class LargeUICollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override init() {
        
        super.init()
        
        // 单元格尺寸
        self.itemSize                = CGSize(width: 70, height: 70)
        // section 内间距
        self.sectionInset            = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
        // 横排单元格最小间距
        self.minimumInteritemSpacing = 40
        // 单元格最小行间距
        self.minimumLineSpacing      = 5
        // CollectionView滚动方向
        self.scrollDirection         = .Vertical
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}  

ShowCollectionViewCell

import UIKit

let identifier = "Identifier"

class ShowCollectionViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.backgroundColor = UIColor.redColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}  

ViewController

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var collectionView: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化UICollectionView并指定一个UICollectionViewFlowLayout
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: LargeUICollectionViewFlowLayout())
        collectionView?.registerClass(ShowCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier)
        collectionView?.dataSource = self
        collectionView?.delegate   = self
        
        view.addSubview(collectionView!)
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        return 5
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    
        return 3
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
        
        return cell
    }


}  
重要的参数
【iOS】UICollectionView_第2张图片
重要的参数.png

二 实现网络请求

效果
实现网络请求.gif
源码

修改ShowCollectionViewCell

import UIKit

let identifier = "Identifier"

class ShowCollectionViewCell: UICollectionViewCell {
    
    var showImageView: UIImageView?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.backgroundColor = UIColor.whiteColor()
        
        var rect: CGRect = self.bounds
        rect.origin.x    += 3
        rect.origin.y    += 3
        rect.size.width  -= 6
        rect.size.height -= 6
        
        showImageView = UIImageView(frame:rect)
        
        self.addSubview(showImageView!)
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}  

修改ViewController

import UIKit

let sourceUrl = "http://www.duitang.com/album/1733789/masn/p/0/100/"

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var collectionView: UICollectionView?
    var dataArray:      [AnyObject]?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化数据源
        dataArray = [AnyObject]()

        // 初始化UICollectionView并指定一个UICollectionViewFlowLayout
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: LargeUICollectionViewFlowLayout())
        collectionView?.registerClass(ShowCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier)
        collectionView?.dataSource = self
        collectionView?.delegate   = self
        
        view.addSubview(collectionView!)
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
            
            // 获取json数据
            let data = NSData(contentsOfURL: NSURL(string: sourceUrl)!)
            
            // 转换数据
            if let dataDic = try? NSJSONSerialization.JSONObjectWithData(data!, options: [.MutableContainers, .MutableLeaves]) as! [String : AnyObject]{
            
                let array = dataDic["data"]!["blogs"] as! [AnyObject]
                
                for value in array {
                
                    let temp = value as! [String : AnyObject]
                    
                    print(temp["isrc"])
                    self.dataArray?.append(temp["isrc"]!)
                    
                }
            }
            
            // 主线程更新
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                self.collectionView?.reloadData()
            })
        }
        
    }
    
    // MARK: UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        return (self.dataArray?.count)!
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    
        return 3
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ShowCollectionViewCell
        
        cell.showImageView?.sd_setImageWithURL(NSURL(string: self.dataArray![indexPath.row] as! String))
        
        return cell
    }


}

  

三 实时更换layout

效果
更换layout.gif
源码
import UIKit

class AnotherCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override init() {
        
        super.init()
        
        // 单元格尺寸
        self.itemSize                = CGSize(width: 150, height: 200)
        // section 内间距
        self.sectionInset            = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
        // 横排单元格最小间距
        self.minimumInteritemSpacing = 40
        // 单元格最小行间距
        self.minimumLineSpacing      = 5
        // CollectionView滚动方向
        self.scrollDirection         = .Vertical
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}  
代码调整
【iOS】UICollectionView_第3张图片
�代码调整1.png
【iOS】UICollectionView_第4张图片
�代码调整2.png

四 下载源码

下载源码

你可能感兴趣的:(【iOS】UICollectionView)