iOS UICollectionView 計(jì)算高度(二)

iOS UICollectionView estimatedItemSize 自定適應(yīng)高度(一)

效果圖

主要代碼在GATagFlowLayout里面币呵,還有代理計(jì)算高度。
如果需要展示其他類型cell 增加section分組的數(shù)量 然后在GATagFlowLayout計(jì)算寬高和位置熊响。注意最后的lastItemRect結(jié)果賦值。

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
    }
}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市苍姜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌悬包,老刑警劉巖衙猪,帶你破解...
    沈念sama閱讀 218,682評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異布近,居然都是意外死亡垫释,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門撑瞧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)棵譬,“玉大人,你說(shuō)我怎么就攤上這事季蚂∶4” “怎么了?”我有些...
    開封第一講書人閱讀 165,083評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵扭屁,是天一觀的道長(zhǎng)算谈。 經(jīng)常有香客問(wèn)我,道長(zhǎng)料滥,這世上最難降的妖魔是什么然眼? 我笑而不...
    開封第一講書人閱讀 58,763評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮葵腹,結(jié)果婚禮上高每,老公的妹妹穿的比我還像新娘。我一直安慰自己践宴,他們只是感情好鲸匿,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著阻肩,像睡著了一般带欢。 火紅的嫁衣襯著肌膚如雪运授。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,624評(píng)論 1 305
  • 那天乔煞,我揣著相機(jī)與錄音吁朦,去河邊找鬼。 笑死渡贾,一個(gè)胖子當(dāng)著我的面吹牛逗宜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播空骚,決...
    沈念sama閱讀 40,358評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼纺讲,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了府怯?” 一聲冷哼從身側(cè)響起幸海,我...
    開封第一講書人閱讀 39,261評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤药磺,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后抒抬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體复局,經(jīng)...
    沈念sama閱讀 45,722評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡冲簿,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了亿昏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片峦剔。...
    茶點(diǎn)故事閱讀 40,030評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖角钩,靈堂內(nèi)的尸體忽然破棺而出吝沫,到底是詐尸還是另有隱情,我是刑警寧澤递礼,帶...
    沈念sama閱讀 35,737評(píng)論 5 346
  • 正文 年R本政府宣布惨险,位于F島的核電站,受9級(jí)特大地震影響脊髓,放射性物質(zhì)發(fā)生泄漏辫愉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評(píng)論 3 330
  • 文/蒙蒙 一将硝、第九天 我趴在偏房一處隱蔽的房頂上張望恭朗。 院中可真熱鬧,春花似錦依疼、人聲如沸痰腮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)膀值。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間虫腋,已是汗流浹背骄酗。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留悦冀,地道東北人趋翻。 一個(gè)月前我還...
    沈念sama閱讀 48,237評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像盒蟆,于是被迫代替她去往敵國(guó)和親踏烙。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容