swift中UICollectionView的使用headerview/footerview/cell/model

github学习地址:https://github.com/potato512/SYSwiftLearning

效果


源码

// MARK: - 数据
func setLocalData()
{
        self.mainArray = NSMutableArray()
        for number in 1...5
        {
            let text = String(format: "第 %d 个",arguments: [number])
            
            let model = Model()
            model.text = text
            
            self.mainArray.addobject(model);
        }
}
// MARK: - 视图
    
func setUI()
{
        // 滚动方向
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
        // 实例化
        self.mainCollectionView = UICollectionView(frame: self.view.bounds,collectionViewLayout: layout)
        // 添加到父视图
        self.view.addSubview(self.mainCollectionView);
        // 属性设置
        self.mainCollectionView.autoresizingMask = .FlexibleHeight
        self.mainCollectionView.backgroundColor = UIColor.blueColor()
        self.mainCollectionView.dataSource = self
        self.mainCollectionView.delegate = self

        // 注册一个cell
        self.mainCollectionView!.registerClass(CollectionViewCell.self,forCellWithReuseIdentifier:cellIdentifier)
        // 注册一个headView
        self.mainCollectionView!.registerClass(CollectionReusableViewHeader.self,forSupplementaryViewOfKind:UICollectionElementKindSectionHeader,withReuseIdentifier: headerIdentifier)
        // 注册一个footView
        self.mainCollectionView!.registerClass(CollectionReusableViewFooter.self,forSupplementaryViewOfKind:UICollectionElementKindSectionFooter,withReuseIdentifier: footerIdentifier)
        
        // 设置页眉、页脚、cell的宽高,及间隔
        // 方法1 属性化设置(显示有点异常),或方法2-代理方法设置
//        layout.itemSize = CGSizeMake(widthCell,heightCell) // cell的宽高
//        layout.minimumLinespacing = 10.0  // cell的上下间隔
//        layout.minimumInteritemSpacing = 10.0 // cell的左右间隔
//        layout.headerReferenceSize = CGSizeMake(width,heightHeader) // 页眉宽高
//        layout.footerReferenceSize = CGSizeMake(width,heightFooter) // 页脚宽高
}
// MARK: - UICollectionViewDataSource,UICollectionViewDelegate
    
// MARK: header/footer的视图
// 返回多少个组
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
        return 10
}
    
// 返回HeadView的宽高
func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,referenceSizeforHeaderInSection section: Int) -> CGSize
{
        return CGSize(width: width,height: heightHeader)
}
    
// 返回footview的宽高
func collectionView(collectionView: UICollectionView,referenceSizeforFooterInSection section: Int) -> CGSize
{
        return CGSizeMake(width,heightFooter)
}
    
// 返回自定义HeadView或者FootView,我这里以headview为例
func collectionView(collectionView: UICollectionView,viewForSupplementaryElementOfKind kind: String,atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
        var reusableview:UICollectionReusableView!
        
        if kind == UICollectionElementKindSectionHeader
        {
            reusableview = collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: headerIdentifier,forIndexPath: indexPath) as! CollectionReusableViewHeader
            reusableview.backgroundColor = UIColor.greenColor()
            
            (reusableview as! CollectionReusableViewHeader).label.text = String(format: "第 %d 个页眉",arguments: [indexPath.section])
        }
        else if kind == UICollectionElementKindSectionFooter
        {
            reusableview = collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: footerIdentifier,forIndexPath: indexPath) as! CollectionReusableViewFooter
            reusableview.backgroundColor = UIColor.brownColor()
            
            (reusableview as! CollectionReusableViewFooter).label.text = String(format: "第 %d 个页脚",arguments: [indexPath.section])
        }
        
        return reusableview
}
// MARK: - cell视图
    
// 返回多少个cell
func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int
{
        return self.mainArray.count
}
    
/**
注意cell的大小与间距的关系,即cell的相对于父视图的大小受上下左右间距的大小影响,以及每个row显示的cell个数的影响。主要是计算宽度。
如:每行显示2个,且上下左右间距为10.0,那么cell的大小相对于父视图来计算则是:cell的宽 = (父视图的宽 - 左右间距的大小 * (2 + 1)) / 2;cell的
*/
// 返回cell的宽高
func collectionView(collectionView: UICollectionView!,layout collectionViewLayout: UICollectionViewLayout!,sizeforItemAtIndexPath indexPath: NSIndexPath!) -> CGSize
{
        return CGSizeMake(widthCell,heightCell)
}
    
// 返回cell 上下左右的间距
func collectionView(collectionView: UICollectionView,insetForSectionAtIndex section: Int) -> UIEdgeInsets
{
        return UIEdgeInsetsMake(10.0,10.0,10.0)
}
    
// 返回自定义的cell
func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier,forIndexPath: indexPath) as! CollectionViewCell
        cell.layer.borderWidth = 0.3;
        cell.layer.borderColor = UIColor.lightGrayColor().CGColor
        
        let model = self.mainArray.objectAtIndex(indexPath.row) as! Model
        let text = model.text
        cell.label!.text = text

        return cell
}
// MARK: 点击事件
    
func collectionView(collectionView: UICollectionView,didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let text = String(format: ("你点击了第 %d-%d 个cell"),arguments: [indexPath.section + 1,indexPath.row + 1])
        let alert = UIAlertView(title: nil,message: text,delegate: nil,cancelButtonTitle: "知道了")
        alert.show()
}



// 自定义cell
import UIKit

let cellIdentifier = "CollectionViewCell"

class CollectionViewCell: UICollectionViewCell {
    
    var label:UILabel!
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        // 初始化各种控件
        self.label = UILabel(frame: CGRectMake(5.0,5.0,(widthCell - 5.0 * 2),(heightCell - 5.0 * 2)))
        self.label.numberOfLines = 0
        self.label.font = UIFont.boldSystemFontOfSize(14.0)
        self.label.textColor = UIColor.lightGrayColor()
        self.contentView.addSubview(self.label)

        self.contentView.backgroundColor = UIColor.redColor()
        self.label.backgroundColor = UIColor.yellowColor()
    }

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

}

// 自定义headerview
import UIKit

let headerIdentifier = "CollectionReusableViewHeader"

class CollectionReusableViewHeader: UICollectionReusableView {
    
    var label:UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.label = UILabel(frame: CGRectMake(10.0,0.0,(CGRectGetWidth(self.bounds) - 10.0 * 2),heightHeader))
        self.addSubview(self.label)
    }

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

// 自定义footer view
import UIKit

let footerIdentifier = "CollectionReusableViewFooter"

class CollectionReusableViewFooter: UICollectionReusableView {
    
    var label:UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.label = UILabel(frame: CGRectMake(10.0,heightFooter))
        self.addSubview(self.label)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// 自定义model
import UIKit

let width = UIScreen.mainScreen().bounds.size.width
let widthCell = (width - 10.0 * 3) / 2
let heightHeader:CGFloat = 40.0
let heightFooter:CGFloat = 20.0
let heightCell:CGFloat = 80.0

class Model: NSObject {

    var text:String!
    
    override init() {
        super.init()
    }
    
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...