iOS UICollectionView 计算高度(二)

iOS UICollectionView estimatedItemSize 自定适应高度(一)

效果图

主要代码在GATagFlowLayout里面,还有代理计算高度。
如果需要展示其他类型cell 增加section分组的数量 然后在GATagFlowLayout计算宽高和位置。注意最后的lastItemRect结果赋值。

import UIKit
class GATagCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var tagLabel: UILabel!
    var model: String! {
        didSet {
            tagLabel.text = model
        }
    }
}
GATagCollectionViewCell.xib 如下图
GATagCollectionViewCell.xib
//
//  GATagCollectionViewController.swift
//  YYFramework
//
//  Created by 侯佳男 on 2018/12/28.
//  Copyright © 2018年 houjianan. All rights reserved.
//

import UIKit

class GATagCollectionViewController: YYBaseCollectionViewController {

    lazy var layout: GATagFlowLayout = {
        let l = GATagFlowLayout()
        l.flowEdgeInset = UIEdgeInsets(top: 20, left: 10, bottom: 15, right: 10)
        l.columSpace = 10
        l.rowSpaces = [10]
        l.delegate = self
        return l
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource = ["123123", "123123", "2312123312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231", "12", "1231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123", "12312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312300", "123123123", "1231123123123123123121231231231231231212331231231212323123", "123123123", "123123123", "123123123", "123123", "2312123312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231", "12", "1231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123", "12312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312312312312312123123123123123121231231231231231212312300", "123123123", "1231123123123123123121231231231231231212331231231212323123", "123123123", "123123123", "123123123"]
    }

    override func base_initCollectionViews() {
        super.base_initCollectionViews()
        collectionView.collectionViewLayout = layout
        
        collectionView.yy_register(nibName: GATagCollectionViewCell.identifier)
    }
    
    func stringSize(s: String) -> CGSize {
        if s.count == 0 {
            return CGSize.zero
        }
        let font = UIFont.systemFont(ofSize: 14)
        
        let width = UIScreen.main.bounds.size.width - self.layout.flowEdgeInset.left - self.layout.flowEdgeInset.right
        let contentSize = (s as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : font], context: nil).size
        // 30是label距离左右的间距和 // 20距离上下和 
        let size = CGSize(width: min(contentSize.width + 30 + 2, width + 2), height: max(28, contentSize.height + 20))

        return size
    }
}

extension GATagCollectionViewController {
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GATagCollectionViewCell.identifier, for: indexPath) as! GATagCollectionViewCell
        cell.tagLabel.text = dataSource[indexPath.row] as? String
        return cell
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
}

extension GATagCollectionViewController: GATagFlowLayoutDelegate {
    func tag(layout: GATagFlowLayout, indexPath: IndexPath) -> CGSize {
        return stringSize(s: dataSource[indexPath.row] as! String)
    }
}

//
//  GATagFlowLayout.swift
//  YYFramework
//
//  Created by 侯佳男 on 2018/12/28.
//  Copyright © 2018年 houjianan. All rights reserved.
//

/*
func stringSize(s: String) -> CGSize {
    if s.count == 0 {
        return CGSize.zero
    }
    let font = UIFont.systemFont(ofSize: 14)
    let width = UIScreen.main.bounds.size.width - self.layout.flowEdgeInset.left - self.layout.flowEdgeInset.right
    let contentSize = (s as NSString).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : font], context: nil).size
    // 32是label距离左右的间距和 // 20距离上下和
    let size = CGSize(width: min(contentSize.width + 32, width + 2), height: max(28, contentSize.height + 25))
    return size
}
*/
/*
lazy var layout: GATagFlowLayout = {
    let l = GATagFlowLayout()
    l.flowEdgeInset = UIEdgeInsets(top: 20, left: 30, bottom: 15, right: 40)
    l.columSpace = 10
    l.delegate = self
    return l
}()
*/
import UIKit

protocol GATagFlowLayoutDelegate: class {
    func tag(layout: GATagFlowLayout, indexPath: IndexPath) -> CGSize
}

class GATagFlowLayout: UICollectionViewFlowLayout {
    
    weak var delegate: GATagFlowLayoutDelegate?
    
    var columSpace: CGFloat = 0
    var rowSpaces: [CGFloat] = [0] // 第一组
    
    var sectionHeight: CGFloat = 0
    var sectionTopSpace: CGFloat = 0
    var flowEdgeInset: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    var attrsArray: [UICollectionViewLayoutAttributes] = []
    var sectionAttrsArray: [UICollectionViewLayoutAttributes] = []
    
    private var lastItemRect: CGRect!
    
    override init() {
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initData() {
        attrsArray.removeAll()
        self.lastItemRect = CGRect(x: flowEdgeInset.left, y: flowEdgeInset.top, width: 0, height: 0)
    }
    
    override func prepare() {
        super.prepare()
        
        initData()
        
        let sectionCount = collectionView!.numberOfSections
        
        for j in 0..<sectionCount {
            let attribute = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: j))
            attrsArray.append(attribute!)
            
            for i in 0..<collectionView!.numberOfItems(inSection: j) {
                let attribute = layoutAttributesForItem(at: IndexPath(item: i, section: j))
                attrsArray.append(attribute!)
            }
        }
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        var orx: CGFloat = 0
        var ory: CGFloat = 0
        
        var isRowDs: CGFloat = 0
        var isColumnDs: CGFloat = 0
        
        if lastItemRect.maxX != flowEdgeInset.left {
            isColumnDs = columSpace
        }
        
        if lastItemRect.maxY != flowEdgeInset.top {
            isRowDs = rowSpaces[indexPath.section]
        }
        
        let size = delegate?.tag(layout: self, indexPath: indexPath)
        let maxDistance = self.collectionView!.frame.size.width - self.lastItemRect.maxX - isColumnDs  - self.flowEdgeInset.right
        if size!.width > maxDistance {
            orx = self.flowEdgeInset.left
            ory = self.lastItemRect.origin.y + self.lastItemRect.size.height + isRowDs
        } else {
            orx = self.lastItemRect.origin.x + self.lastItemRect.size.width + isColumnDs
            ory = self.lastItemRect.origin.y
        }
        
        attribute.frame = CGRect(x: orx, y: ory, width: size!.width, height: size!.height)
        lastItemRect = attribute.frame
        
        return attribute
    }
    
    override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attribute = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)
        let x: CGFloat = 0
        let y: CGFloat = lastItemRect.maxY + (indexPath.section != 0 ? sectionTopSpace : 0)
        let w: CGFloat = collectionView!.width
        let h: CGFloat = sectionHeight
        attribute.frame = CGRect(x: x, y: y, width: w, height: h)
        lastItemRect = attribute.frame
        return attribute
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrsArray
    }
    
    override var collectionViewContentSize: CGSize {
        let maxContentHeight = lastItemRect.origin.y + lastItemRect.size.height + flowEdgeInset.bottom
        return CGSize(width: 0, height: maxContentHeight)
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}


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

推荐阅读更多精彩内容