ios 如何實(shí)現(xiàn)淘寶一類選擇商品自適應(yīng)長度

你的小可愛已上線

淘寶點(diǎn)擊商品可以進(jìn)行商品的選擇比如大小之類的堪滨,這類可以選擇用collectionView來寫咐刨,下面我講述一下我的項(xiàng)目中所用的界面做一個(gè)簡單的分析和實(shí)現(xiàn)想法昙楚,如果有更好的想法可以分享給我刽肠。

效果.gif

規(guī)格上面的是一個(gè)固定的view纯命,規(guī)格下面第一個(gè)粉框框是collectionView愿题,根據(jù)文字大小實(shí)現(xiàn)動(dòng)態(tài)顯示损俭,數(shù)量一個(gè)框是UICollectionReusableView可以設(shè)為footer

先來分析下如何是實(shí)現(xiàn)動(dòng)態(tài)獲取string長度

//collectionItemSize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: self.getWidthWithText(text: self.dataArr[indexPath.row] as NSString, height: 30*W, font: 12*W)+20*W, height: 30*W)
    }
 //獲取長度
    func getWidthWithText(text:NSString,height:CGFloat,font:CGFloat) -> CGFloat{
        let size = text.boundingRect(with: CGSize.init(width: CGFloat(MAXFLOAT), height: height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: font) ], context: nil)
        return size.width
    }
    

進(jìn)行collectionItemSize寬度賦值,如果是網(wǎng)絡(luò)數(shù)據(jù)我們可以進(jìn)行再model其中加一個(gè)屬性為width把這個(gè)獲取到string寬度進(jìn)行封存潘酗,在cell內(nèi)賦值時(shí)候要對這個(gè)label的寬度重新賦值杆兵,實(shí)現(xiàn)動(dòng)態(tài)顯示寬度。

再來分析下如何實(shí)現(xiàn)單選問題仔夺,這個(gè)問題就很好解決創(chuàng)建一個(gè)全局變量cell琐脏,當(dāng)每次點(diǎn)擊時(shí)候進(jìn)行一次賦值和樣式改變就好了,我還是附上代碼

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as!XBSetAddGoodsCollectionViewCell
        if (self.selectCell != cell) {
            cell.titleLable.backgroundColor = #colorLiteral(red: 0.9921568627, green: 0.5921568627, blue: 0.3254901961, alpha: 1)
            cell.titleLable.textColor = UIColor.white
            if self.selectCell != nil {
                selectCell.titleLable.backgroundColor = #colorLiteral(red: 0.9647058824, green: 0.9647058824, blue: 0.9647058824, alpha: 1)
                selectCell.titleLable.textColor = LabelColor_51
            }
            selectCell = cell
        }else{
            cell.titleLable.backgroundColor = #colorLiteral(red: 0.9921568627, green: 0.5921568627, blue: 0.3254901961, alpha: 1)
            cell.titleLable.textColor = UIColor.white
            selectCell = cell
        }
    }

那么有人肯定問了,你的cell為何可以居左面日裙,這個(gè)問題嘛 網(wǎng)上很多解決辦法 畢竟都是大佬寫好的我也不想自己寫吹艇,畢竟我不是大佬,只是一個(gè)搬磚的昂拂,我就拿來搬了這樣我把方法也分給大家吧受神!到底是哪個(gè)大佬我也忘了,光顧復(fù)制了格侯,哈哈哈哈哈鼻听!

1.首先你創(chuàng)建一個(gè)繼承UICollectionViewFlowLayout的類
/// 對齊方向的枚舉, 可拓展, 命名可根據(jù)自己喜好
enum AlignType : NSInteger {
    case left = 0
    case center = 1
    case right = 2
}

class CollectionViewAlignFlowLayout: UICollectionViewFlowLayout {
    //兩個(gè)Cell之間的距離
    var betweenOfCell : CGFloat{
        didSet{
            self.minimumInteritemSpacing = betweenOfCell
        }
    }
    //cell對齊方式
    var cellType : AlignType = AlignType.center
    //在居中對齊的時(shí)候需要知道這行所有cell的寬度總和
    var sumCellWidth : CGFloat = 0.0
    
    override init() {
        betweenOfCell = 5.0
        super.init()
        scrollDirection = UICollectionViewScrollDirection.vertical
        minimumLineSpacing = 5
        sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
    }
    convenience init(_ cellType:AlignType){
        self.init()
        self.cellType = cellType
    }
    convenience init(_ cellType: AlignType, _ betweenOfCell: CGFloat){
        self.init()
        self.cellType = cellType
        self.betweenOfCell = betweenOfCell
    }
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        let layoutAttributes_super : [UICollectionViewLayoutAttributes] = super.layoutAttributesForElements(in: rect) ?? [UICollectionViewLayoutAttributes]()
        let layoutAttributes:[UICollectionViewLayoutAttributes] = NSArray(array: layoutAttributes_super, copyItems:true)as! [UICollectionViewLayoutAttributes]
        var layoutAttributes_t : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
        for index in 0..<layoutAttributes.count{
            
            let currentAttr = layoutAttributes[index]
            let previousAttr = index == 0 ? nil : layoutAttributes[index-1]
            let nextAttr = index + 1 == layoutAttributes.count ?
                nil : layoutAttributes[index+1]
            
            layoutAttributes_t.append(currentAttr)
            sumCellWidth += currentAttr.frame.size.width
            
            let previousY :CGFloat = previousAttr == nil ? 0 : previousAttr!.frame.maxY
            let currentY :CGFloat = currentAttr.frame.maxY
            let nextY:CGFloat = nextAttr == nil ? 0 : nextAttr!.frame.maxY
            
            if currentY != previousY && currentY != nextY{
                if currentAttr.representedElementKind == UICollectionElementKindSectionHeader{
                    layoutAttributes_t.removeAll()
                    sumCellWidth = 0.0
                }else if currentAttr.representedElementKind == UICollectionElementKindSectionFooter{
                    layoutAttributes_t.removeAll()
                    sumCellWidth = 0.0
                }else{
                    self.setCellFrame(with: layoutAttributes_t)
                    layoutAttributes_t.removeAll()
                    sumCellWidth = 0.0
                }
            }else if currentY != nextY{
                self.setCellFrame(with: layoutAttributes_t)
                layoutAttributes_t.removeAll()
                sumCellWidth = 0.0
            }
        }
        return layoutAttributes
    }
    
    /// 調(diào)整Cell的Frame
    ///
    /// - Parameter layoutAttributes: layoutAttribute 數(shù)組
    func setCellFrame(with layoutAttributes : [UICollectionViewLayoutAttributes]){
        var nowWidth : CGFloat = 0.0
        switch cellType {
        case AlignType.left:
            nowWidth = self.sectionInset.left
            for attributes in layoutAttributes{
                var nowFrame = attributes.frame
                nowFrame.origin.x = nowWidth
                attributes.frame = nowFrame
                nowWidth += nowFrame.size.width + self.betweenOfCell
            }
            break;
        case AlignType.center:
            nowWidth = (self.collectionView!.frame.size.width - sumCellWidth - (CGFloat(layoutAttributes.count - 1) * betweenOfCell)) / 2
            for attributes in layoutAttributes{
                var nowFrame = attributes.frame
                nowFrame.origin.x = nowWidth
                attributes.frame = nowFrame
                nowWidth += nowFrame.size.width + self.betweenOfCell
            }
            break;
        case AlignType.right:
            nowWidth = self.collectionView!.frame.size.width - self.sectionInset.right
            for var index in 0 ..< layoutAttributes.count{
                index = layoutAttributes.count - 1 - index
                let attributes = layoutAttributes[index]
                var nowFrame = attributes.frame
                nowFrame.origin.x = nowWidth - nowFrame.size.width
                attributes.frame = nowFrame
                nowWidth = nowWidth - nowFrame.size.width - betweenOfCell
            }
            break;
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
2.聲明一個(gè)全局變量var flowlayout: CollectionViewAlignFlowLayout!并且實(shí)現(xiàn)代理就好,完事联四!
        flowlayout = CollectionViewAlignFlowLayout(AlignType.left, 10*W)
        flowlayout.minimumLineSpacing = 10*W
        flowlayout.minimumInteritemSpacing = 15*W
        flowlayout.sectionInset = UIEdgeInsets.init(top: 10*W, left: 10*W, bottom: 10*W, right: 10*W)
        
        let collectionView = UICollectionView(frame: CGRect(x:0, y: 0, width:0, height:0), collectionViewLayout: flowlayout)

我的git demo地址:https://github.com/sunrose11/CollectionViewShopCart
下面的加減號(hào) 我是用的別人的 還是那句話自己寫的有bug撑碴,這個(gè)哥們的寫的很好而且很多樣子,就一個(gè)類的代碼量 我很是喜歡朝墩。給大家他的git:https://github.com/jkpang

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末灰羽,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鱼辙,更是在濱河造成了極大的恐慌廉嚼,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倒戏,死亡現(xiàn)場離奇詭異怠噪,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)杜跷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進(jìn)店門傍念,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人葛闷,你說我怎么就攤上這事憋槐。” “怎么了淑趾?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵阳仔,是天一觀的道長。 經(jīng)常有香客問我扣泊,道長近范,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任延蟹,我火速辦了婚禮评矩,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘阱飘。我一直安慰自己斥杜,他們只是感情好虱颗,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蔗喂,像睡著了一般上枕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上弱恒,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天辨萍,我揣著相機(jī)與錄音,去河邊找鬼返弹。 笑死锈玉,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的义起。 我是一名探鬼主播拉背,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼默终!你這毒婦竟也來了椅棺?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤齐蔽,失蹤者是張志新(化名)和其女友劉穎两疚,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體含滴,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡诱渤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了谈况。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片勺美。...
    茶點(diǎn)故事閱讀 40,865評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖碑韵,靈堂內(nèi)的尸體忽然破棺而出赡茸,到底是詐尸還是另有隱情,我是刑警寧澤祝闻,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布占卧,位于F島的核電站,受9級(jí)特大地震影響治筒,放射性物質(zhì)發(fā)生泄漏屉栓。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一耸袜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧牲平,春花似錦堤框、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽启绰。三九已至,卻和暖如春沟使,著一層夾襖步出監(jiān)牢的瞬間委可,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工腊嗡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留着倾,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓燕少,卻偏偏與公主長得像卡者,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子客们,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評論 2 361

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

  • 月亮像是被掰開的橘子 遠(yuǎn)遠(yuǎn)的崇决,在那里掛著 也許是我近視的緣故 好想上去咬它一口 嘗嘗是不是小丑橘 而我卻喜歡酸的
    說什么話不像說謊h閱讀 164評論 0 0
  • 今天是國慶節(jié),祖國的生日底挫,帶著自豪而愉悅的心情恒傻,翻開了這篇文章。 《音樂表演藝術(shù)中的真與美》作者是南京藝術(shù)學(xué)院音樂...
    雨文兒閱讀 875評論 0 0
  • 1.初中所謂的朋友建邓,到高中還會(huì)聯(lián)系么碌冶?(感覺不會(huì)了) 2.同學(xué)經(jīng)常說衣服,我不怎么愛打扮涝缝,穿著舒服就行扑庞,但是有時(shí)會(huì)...
    陌墨離傷閱讀 152評論 0 0
  • 我愛你 低到塵埃里 無法言語 無法自拔 唯有那對你情深義重的眷戀 我的心都在你那里 你能看見嗎?
    石川河女神閱讀 204評論 0 1