UICollectionView多cell样式布局

最近遇到一个需求,一行单元格展示3个item,期间会穿插banner样式单元格,类似下图:

cape_01@2x.png

起初是想用UITableView来实现,但是需要定制展示3个item的cell,比较麻烦,因为后台给的数据就是一个装有各个item的数组,这样还得自己去把数据分组,反正比较麻烦,最后选择了用UICollectionView来实现,但是这样也是需要定制2种样式的item.我们知道tableview定制并且展示多种不同样式的cell是比较容易的, UICollectionView就有点不容易了.经过一番研究,找到解决方案,先记录如下,以备不时之需.

1.继承UICollectionViewFlowLayout定制一个布局类,重写几个核心方法
a.

override func prepare()

b.

override var collectionViewContentSize: CGSize

c.

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

d.

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?

有头视图的再加个这个方法

override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

代码如下

import UIKit

let twoCellWidth: CGFloat = (UIScreen.main.bounds.width - 15 * 4) / 3
let twoCellHeight: CGFloat = twoCellWidth * 1.2

let oneCellWidth: CGFloat = UIScreen.main.bounds.width
let oneCellHeight: CGFloat = oneCellWidth * 0.5

let headerWidth: CGFloat = UIScreen.main.bounds.width
let headerHeight: CGFloat = 190

protocol CustomLayoutDataSource: NSObjectProtocol {
    func treasureLayoutEachFrameForItemAtIndexPath(layout: CustomLayout,indexPath: IndexPath) -> CGRect
    func collectionViewContentSize(layout: CustomLayout) -> CGSize
}

class CustomLayout: UICollectionViewFlowLayout {

    weak var dataSource: CustomLayoutDataSource?

    override func prepare() {
        super.prepare()
    }
    
    override var collectionViewContentSize: CGSize {
        get{
            return dataSource?.collectionViewContentSize(layout: self) ?? CGSize.zero
        }
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attr = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
        attr.frame = dataSource?.treasureLayoutEachFrameForItemAtIndexPath(layout: self, indexPath: indexPath) ?? CGRect.zero
        return attr
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attrs = [UICollectionViewLayoutAttributes]()
        
        for j in 0..<(collectionView?.numberOfSections)! {
            
            let indexPath: IndexPath = IndexPath(item: 0, section: j)
            
            attrs.append(layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath)!)
            
            for i in 0..<(collectionView?.numberOfItems(inSection: j))! {
                let indexPath = IndexPath(item: i, section: j)
                attrs.append(layoutAttributesForItem(at: indexPath)!)
            }
        }
        return attrs
    }
    
    override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        if elementKind == UICollectionElementKindSectionHeader {
            let attr = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: indexPath)
            attr.frame = CGRect(x: 0,y: 0,width: headerWidth,height: headerHeight)
            return attr
        }
        return nil
    }
    
}

定义一个数据源代理方法CustomLayoutDataSource

2.viewControllor初始化视图,注册item样式,头视图

let layout = CustomLayout()
        layout.dataSource = self
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        
        collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.lightGray
        collectionView.dataSource = self
        collectionView.delegate = self
        view.addSubview(collectionView)
        
        collectionView.register(CustomTwoCell.self, forCellWithReuseIdentifier: "twoCell")
        collectionView.register(CustomOneCell.self, forCellWithReuseIdentifier: "oneCell")
        collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")

3.实现相应的代理方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionElementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! HeaderView
            headerView.backgroundColor = UIColor.yellow
            return headerView
        }
        
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell: UICollectionViewCell
        
        let dataDic: NSDictionary = dataArray[indexPath.row] 
        let type = dataDic["type"] as! Int
        if type == 2 {
           cell = collectionView.dequeueReusableCell(withReuseIdentifier: "twoCell", for: indexPath) as! CustomTwoCell
           cell.backgroundColor = UIColor.green
        }else{
           cell = collectionView.dequeueReusableCell(withReuseIdentifier: "oneCell", for: indexPath) as! CustomOneCell
            cell.backgroundColor = UIColor.red
        }
        return cell
    }
    
    func collectionViewContentSize(layout: CustomLayout) -> CGSize {
        var twoCellCount: Int = 0
        var oneCellCount: Int = 0
        
        for (_,dic) in dataArray.enumerated() {
            let type: Int = dic["type"] as! Int
            if type == 2{
                twoCellCount += 1
            }else{
                oneCellCount += 1
            }
        }
        
        var headerheight: CGFloat = 0

        headerheight = headerHeight + layout.minimumLineSpacing
        
        let twoCellHeightT: CGFloat = CGFloat(ceilf((Float(Float(twoCellCount) / 3)))) * twoCellHeight
        let oneCellHeightT: CGFloat = CGFloat(oneCellCount) * oneCellHeight
        let paddingHeightT: CGFloat = CGFloat(ceilf((Float(Float(twoCellCount) / 3))) + Float(oneCellCount)) * layout.minimumLineSpacing
        
        
        let size = CGSize(width: view.bounds.width, height: twoCellHeightT + oneCellHeightT + paddingHeightT + headerheight)
        
        return size
    }
    
    func treasureLayoutEachFrameForItemAtIndexPath(layout: CustomLayout, indexPath: IndexPath) -> CGRect {
        var twoCellCount: Int = 0
        var oneCellCount: Int = 0
        var cellType: Int?
        
        
        for (index, dic) in dataArray.enumerated() {
            let type = dic["type"] as? Int
            if indexPath.item == index {
                cellType = type
                break
            }else if type == 2 {
                twoCellCount += 1
            }else{
                oneCellCount += 1
            }
        }
        
        
        var x: CGFloat = 15
        var y: CGFloat = 0
        var width: CGFloat = 0
        var height: CGFloat = 0
        
        let twoCellHeightT: CGFloat = CGFloat((twoCellCount / 3)) * twoCellHeight
        let oneCellHeightT: CGFloat = CGFloat(oneCellCount) * oneCellHeight
        let paddingHeightT: CGFloat = CGFloat((twoCellCount / 3) + oneCellCount) * layout.minimumLineSpacing
        
        y = headerHeight + layout.minimumLineSpacing
        
        if cellType == 2 {
            width = twoCellWidth
            height = twoCellHeight
            
            if !(isCellOnLeftByTreasure(treasure: twoCellCount, oneCount: oneCellCount)) {
                x = (width + layout.minimumInteritemSpacing) * CGFloat(indexCount) + layout.minimumInteritemSpacing;
            }
            y += (twoCellHeightT + oneCellHeightT + paddingHeightT)
            
        }else{
            x = 0
            width = oneCellWidth
            height = oneCellHeight
            
            y += (twoCellHeightT + oneCellHeightT + paddingHeightT)
        }
        return CGRect(x: x,y: y,width: width,height: height)
    }
    
    func isCellOnLeftByTreasure(treasure: Int,oneCount: Int) -> Bool {
        if (treasure + oneCount * 3) % 3 == 0 {
            indexCount = 0
            return true;
        } else {
            indexCount += 1
            return false;
        }
    }

主要是在布局类的代理方法里计算坐标,高度,如代码所示

最后看下效果图:

多cell样式.gif

黄色是头视图,红色是banner样式的item,绿色是一行多个数据的item样式,抽空把代码放在github上,恩恩.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,945评论 4 60
  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 3,779评论 1 22
  • 夜睡了一万年不曾醒来 黑色的幕布好象不打算再掀开 风,狰狞地嚎叫 雨,无奈着泪流 要往哪里走 何处是尽头 灵魂留在...
    一蓑烟雨feng阅读 301评论 3 6
  • 第六章:花外看花花梦醒,亭中猜谜谜赠香 玉树飘飖兮(目录) 天色渐晚,秋夜寒风凉。 飘飖呆看瑾兮良久,被这冷风吹得...
    鹞一阅读 459评论 0 6
  • 1. 拜读了鲁迅先生的《浪·海与一支玫瑰》后,曾几度想去拜访他,可一直...
    微微风吟阅读 757评论 0 0