前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS UICollectionView的用法

iOS UICollectionView的用法

作者头像
码客说
发布2019-10-22 14:12:38
1.2K0
发布2019-10-22 14:12:38
举报
文章被收录于专栏:码客码客

使用流式布局

继承

UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

设置

Swift

代码语言:javascript
复制
self.collectionView.register(UINib.init(nibName: "MeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MeCollectionViewCell");
self.collectionView.showsHorizontalScrollIndicator = false;
self.collectionView.showsVerticalScrollIndicator = false;
self.collectionView.backgroundColor = UIColor.clear;
self.collectionView.isScrollEnabled = false;
let flowLayout = UICollectionViewFlowLayout();
flowLayout.scrollDirection = UICollectionViewScrollDirection.vertical;
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
self.collectionView.collectionViewLayout = flowLayout;
self.collectionView.dataSource = self;
self.collectionView.delegate = self;

OC

代码语言:javascript
复制
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (strong, nonatomic) NSMutableArray<NSMutableArray<OrderPicModel *> *> *tableData;
代码语言:javascript
复制
[self.collectionView registerNib:[UINib nibWithNibName:@"OrderPicsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"OrderPicsCollectionViewCell"];
self.collectionView.showsHorizontalScrollIndicator = false;
self.collectionView.showsVerticalScrollIndicator = false;
self.collectionView.scrollEnabled = true;
self.collectionView.pagingEnabled = true;
    
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
self.collectionView.collectionViewLayout = flowLayout;
self.collectionView.dataSource = self;
self.collectionView.delegate = self;

代理方法

Swift

代码语言:javascript
复制
var colletcionData:[[String:String]] = [
        ["type": "1","text":"签到","image":"uc_sign@3x.png"],
        ["type": "2","text":"积分历史","image":"uc_integration@3x.png"],
        ["type": "3","text":"更多","image":"uc_more@3x.png"]
    ]
代码语言:javascript
复制
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1;
}
    
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return colletcionData.count;
}
    
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let itemdata = colletcionData[indexPath.row];
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MeCollectionViewCell", for: indexPath) as! MeCollectionViewCell;
    cell.imageView.image = UIImage(named: itemdata["image"]!);
    cell.textLabel.text = itemdata["text"];
    if(indexPath.row+1 % 3 == 0){
        cell.lineImageView.isHidden = true;
    }
    return  cell;
}
    
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.collectionView.frame.width/3, height: 100);
}
    
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
}

OC

代码语言:javascript
复制
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.tableData.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.tableData[section].count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    OrderPicModel *model = self.tableData[indexPath.section][indexPath.row];
    OrderPicsCollectionViewCell *picCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OrderPicsCollectionViewCell" forIndexPath:indexPath];
    picCell.imageView.image = [UIImage imageNamed:model.imageUrl];
    return picCell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.collectionView.frame.size.width, self.collectionView.frame.size.height);
}

- (void)collectionView:(UICollectionView *)collectionView
  didEndDisplayingCell:(UICollectionViewCell *)cell
    forItemAtIndexPath:(NSIndexPath *)indexPath {
    // 获取当前显示的cell的下标
    NSIndexPath *firstIndexPath = [[self.collectionView indexPathsForVisibleItems] firstObject];
    // 赋值给记录当前坐标的变量
    self.pageControl.currentPage = firstIndexPath.row;
}

设置Header或Footer

生成头

我这里用的xib,对应的class文件如下

代码语言:javascript
复制
class QuestionBookHeader: UICollectionReusableView {
    @IBOutlet weak var titleLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    } 
}

注册

代码语言:javascript
复制
self.collectionView.registerNib(UINib(nibName: "QuestionBookHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "QuestionBookHeader")

代理方法

代码语言:javascript
复制
//返回自定义HeadView或者FootView,我这里以headview为例
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
    
    let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "QuestionBookHeader", forIndexPath: indexPath) as! QuestionBookHeader;
    if(indexPath.section == 0){
        header.titleLabel.text = "我的分类"
    }else{
        header.titleLabel.text = "推荐分类"
    }
    
    return header
}

使用自定义布局

继承

UICollectionViewDataSource,UICollectionViewDelegate

自定义布局

代码语言:javascript
复制
import UIKit
class MainLayout : UICollectionViewLayout {
    
    // 内容区域总大小,不是可见区域
    override func collectionViewContentSize() -> CGSize {
        return CGSizeMake(
            collectionView!.bounds.size.width,
            320
        )
    }
    
    // 所有单元格位置属性
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributesArray = [UICollectionViewLayoutAttributes]()
        let cellCount = self.collectionView!.numberOfItemsInSection(0)
        for i in 0..<cellCount {
            let indexPath =  NSIndexPath(forItem:i, inSection:0)
            let attributes =  self.layoutAttributesForItemAtIndexPath(indexPath)
            attributesArray.append(attributes!)
        }
        return attributesArray
    }
    
    // 这个方法返回每个单元格的位置和大小
    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        //当前单元格布局属性
        let attribute =  UICollectionViewLayoutAttributes(forCellWithIndexPath:indexPath)
        //当前行的Y坐标
        let topSpace:CGFloat = 10;
        let space:CGFloat = 6;
        let leftSpace:CGFloat = 10;
        let itemWidth:CGFloat = (collectionView!.bounds.size.width - leftSpace*2 - space)/2;
        var itemHeight:CGFloat = 214;
        var itemHeight2:CGFloat = 104;
        if(ZJ_SysUtils.getDeviceType() == ZJ_SysUtils.DeviceType.iPhone6){
            itemHeight2 = itemHeight2 * 1.3;
            itemHeight = itemHeight2 * 2 + space;
        }
        let rightX:CGFloat =  leftSpace + itemWidth + space;
        let right1Y = topSpace;
        let right2Y = topSpace + itemHeight2 + space;
        let right3Y = topSpace + itemHeight + space;
        
        let item = indexPath.item;
        if (item == 0) {
            attribute.frame = CGRectMake(leftSpace, right1Y, itemWidth, itemHeight)
        } else if (item == 1) {
            attribute.frame = CGRectMake(rightX, right1Y, itemWidth, itemHeight2)
        } else if (item == 2) {
            attribute.frame = CGRectMake(rightX, right2Y, itemWidth, itemHeight2)
        } else if (item == 3) {
            attribute.frame = CGRectMake(leftSpace, right3Y, itemWidth, itemHeight2)
        } else if (item == 4) {
            attribute.frame = CGRectMake(rightX, right3Y, itemWidth, itemHeight2)
        }
        return attribute
    }
}

设置

代码语言:javascript
复制
collectionView.registerNib(UINib.init(nibName: "MainBigCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "mainBigCollCell");
collectionView.registerNib(UINib.init(nibName: "MainSmallCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "mainSmallCollCell");
collectionView.collectionViewLayout = MainLayout();
collectionView.dataSource = self;
collectionView.delegate = self;

代理方法

代码语言:javascript
复制
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1;
}
    
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5;
}
    
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
}
    
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-01-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用流式布局
    • 继承
      • 设置
        • 代理方法
        • 设置Header或Footer
          • 生成头
            • 注册
              • 代理方法
              • 使用自定义布局
                • 继承
                  • 自定义布局
                    • 设置
                      • 代理方法
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档