IOS OC關(guān)于如何讓collectionview左對齊

首先知識點
1 獲取一個view的最右邊的x值
CGRectGetMaxX(prevLayoutAttributes.frame);
2 獲取一個view的最下面y值
CGRectGetMaxY(prevLayoutAttributes.frame);
3 uicollectionViewFlowLayout有個layoutAttributesForElementsInRect方法,這個方法返回所有的cell的布局參數(shù)的數(shù)組
4 解決方法
重寫layoutAttributesForElementsInRect方法


  • (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
    // 獲取系統(tǒng)幫我們計算好的Attributes
    NSArray *answer = [super layoutAttributesForElementsInRect:rect];

    // 遍歷結(jié)果
    for(int i = 1; i < [answer count]; ++i) {

      // 獲取cell的Attribute,根據(jù)上一個cell獲取最大的x,定義為origin
      UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
      UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
      
      //此處根據(jù)個人需求,我的需求里面有head cell兩類,我只需要調(diào)整cell,所以head直接過濾
      if([currentLayoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]){
          continue;
      }
      
      NSInteger preX = CGRectGetMaxX(prevLayoutAttributes.frame);
      NSInteger preY = CGRectGetMaxY(prevLayoutAttributes.frame);
      NSInteger curY = CGRectGetMaxY(currentLayoutAttributes.frame);
      
      // 設(shè)置cell最大間距
      NSInteger maximumSpacing = 0;
      
      // 如果當(dāng)前cell和precell在同一行
      if(preY == curY){
          //滿足則給當(dāng)前cell的frame屬性賦值
          //不滿足的cell會根據(jù)系統(tǒng)布局換行
          CGRect frame = currentLayoutAttributes.frame;
          frame.origin.x = preX + maximumSpacing;
          currentLayoutAttributes.frame = frame;
      }
    

    }
    return answer;
    }


參考
http://www.itdecent.cn/p/f042944a605d

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容