CollectionViewCell 自动高度与自动布局

CollectionViewCell 自动高度

写在前面:
UITableViewCell的自动高度很方便,开发中很多时候首选tableView的原因也是因为这个,可以减少很多高度或者动态高度的计算过程。
CollectionViewCell 其实也是可以自动高度的, 需要重写实现一个方法func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes

1. CollectionViewCell实现自动高度

CollctionViewCell 要实现自动高度,除了UI控件在布局上要像在TableViewCell一样做到用约束撑开contentView之外,还要实现func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes方法, 实现这个方法的目的其实也是通过手动计算的方式来返回真实的高度。

比如:假如collectionViewCell中有一个textView(或者label什么的), 现在需求是这个cell的高度要随着textView中的自动换行而增大,那么在这个方法中可以这样计算:

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var newFrame = layoutAttributes.frame
        newFrame.size.height = (textView.text?.isSpaceOrEmpty ?? true) ? 0 : ceil(size.height)
        layoutAttributes.frame = newFrame
        return layoutAttributes
}

这样在textView字数发生变化时就会调用这个方法,实时计算实际高度并重新布局了。

2. IGListKit中的CollectionViewCell的高度计算

在IGListKit中实现sectionController时,必要实现sizeForItem这个方法,在这个方法里对每种cell手动计算它的实际高度并返回,有时候也要配合上面自动布局需要实现的方法共同计算并返回真实高度。

比如,CollectionViewCell中有一个支持多行的label, 在sectionController的sizeForItem 中首先要手动计算这些字所占高度,再加上label上下间隙高度。

计算字所占高度通常可通知创建一个模拟label的实际计算,注意这个模拟label的字体以及样式要和真实的label保持一致。

static func height(text: String,
                       width: CGFloat,
                       topPadding: CGFloat = 20,
                       bottomPadding: CGFloat = 20) -> CGFloat {

        let fakeLabel = XOLabel(frame: CGRect(x: 0,
                                              y: 0,
                                              width: width - 40,
                                              height: .greatestFiniteMagnitude))
        fakeLabel.numberOfLines = 0
        fakeLabel.font = .caption1
        fakeLabel.text = text
        fakeLabel.sizeToFit()

        return fakeLabel.bounds.size.height + topPadding + bottomPadding
}

注意: 因为这个cell中的实际label.numbersOfLines = 0,需要实现自动高度,所以依然要实现func preferredLayoutAttributesFitting方法才能实现完全撑开cell。

算完之后在sizeForItem中就可以为这个cell返回实际高度了。

3. CollectionView的自动高度

有时候需要实现在tableViewCell中嵌入collectionView, 虽然tableViewCell可以实现自动高度,但因为collectionView是可以滚动的,虽然可以像textView一样禁掉滚动属性,但毕竟是collectionView, 有时候加载的东西比较多,实现不了像textView一样实时更新高度。
除非CollectionViewCell中的item大小是可以确定的,这种情况下可以实现整个tableViewCell的自动高度。

如果collectionViewCell的item大小不确定,有什么办法实现tableViewCell的自动高度呢?
网上查到的方法是大概是这样说的:在TabelViewCell的layoutSubviews重新方法中加入以下代码

self.contentView.frame = bounds  // 先为contentView设置frame,使得子视图有布局依据,使得contentView不会被忽略而被线程渲染。
self.collectionView.reloadData()
let contentSize = collectionView.contentSize
self.frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)

这样看起来挺合理的,但实现运行起来出问题了,高度不对,还出现死循环。可能是不适用于我当时的demo。

tableViewCell中嵌入collectionView

所幸我需要实现的collectionView的item比较单一,这样可以实际去计算实际高度,于是将所有间隙找出,一个一个item计算其宽度,当前行放不下了就换行+高:

private func heightForCell(withFilters filters: [String]) -> CGFloat {
        var widthRemaining = LayoutParameter.collectionWidth
        var height: CGFloat = LayoutParameter.collectionViewTopPadding
        let fakeLabel = XOLabel()
        fakeLabel.font = .body

        filters.enumerated().forEach { (index, filter) in
            fakeLabel.text = filter
            if index == 0 {
                let firstLineHeightOfItems = LayoutParameter.itemHeight
                height += firstLineHeightOfItems
            }
            fakeLabel.sizeToFit()
            let itemWidth = LayoutParameter.labelLeftPad + fakeLabel.width() + LayoutParameter.labelRightPad

            //当当前行不足以再放多一个item时换行,+高度
            if widthRemaining - itemWidth - LayoutParameter.itemSpace <= 0 {
                height += (LayoutParameter.verticalSpace + LayoutParameter.itemHeight)
                widthRemaining = LayoutParameter.collectionWidth
                // 换行结束将行宽还原
            }
            widthRemaining -= (LayoutParameter.itemSpace + itemWidth)
        }
        return height
}

这样就可以计算出整个collectionView的高度了,只要间隙的值准备,计算的结果几乎是正确的。

4. collectionView 自定义布局

collectionView 横向布局、纵向布局、 items 左右对齐、上下对齐

1. items 左对齐

collectionView items 默认是分散对齐的,如果需要实现类似以下的左对齐效果需要自定义布局。


items 左对齐

左对齐的实现方式比较简单,直接重写UICollectionViewFlowLayout下的layoutAttributesForElements( )

public final class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0  //设置负值,保证第一次满足条件
        attributes?.forEach { layoutAttribute in    //item
            if layoutAttribute.frame.origin.y >= maxY {  //如果还没换行则不满足条件,换行了才满足条件使得leftMargin回到0
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing  //左对齐
            maxY = max(layoutAttribute.frame.maxY, maxY)
        }
        return attributes
    }
}
item.y
//然后在collectionView的layout中可能这样使用
private let layout: LeftAlignedCollectionViewFlowLayout = {
        let layout = LeftAlignedCollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        return layout
}( )

collectionView.collectionViewLayout = layout
//collectionView.isScrollEnabled = false
2. 右对齐

右对齐类似,只是计算中有点点不一样

public final class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var rightMargin = rect.maxX
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                rightMargin = rect.maxX - 20
            }

            layoutAttribute.frame.origin.x = rightMargin - layoutAttribute.frame.width

            rightMargin -= layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY, maxY)
        }
        return attributes
    }
}
右对齐
3. 底部对齐

在做一些聊天页面时,当刚开始建立对话,只有一两个cell时,希望像Slack 软件一样做到底部对齐,可以这样做。

 public final class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

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