CollectionView-簡單的布局:圓形布局

1.對于圓形布局的設置:


Snip20150904_1.png

1.1 不同于流水布局,因為流水布局的界面 只有水平方向上的布置以及豎直方向上的布置兩種.
1.2 新的布局 為圓形布局,是所有的圖片圍成一圈的排列.所以新的布局不能繼續繼承于流水布局,而屬于自己去安排布局,繼承于他的基類 UICollectionViewLayout.

2.和水平縮放布局很像,對于布局元素 應該在- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect此方法中安排顯示的布局集合.
3.重寫- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds使布局因素能夠實時更新

Snip20150904_2.png

代碼如下:

// 確保能實時更新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}
// 進行圓形布局,設置其每個元素的相關因素(主要是它的 frame,中心點)
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
// 創建可變數組,用于儲存所有的布局因素
    NSMutableArray *layoutAtts = [NSMutableArray array];   
// 取出對應布局中的 collectionView 的元素的數目(為的就是給一個個cell 獨立設置其的布局)
    NSInteger count =  [self.collectionView numberOfItemsInSection:0];
// 設置每個 cell 的高度和寬度
    CGFloat WH = 50;
// 取出圓形視圖的中心點 (也就是 collectionView 的中心點)    
CGFloat centerX = self.collectionView.frame.size.width * 0.5;
    CGFloat centerY = self.collectionView.frame.size.height * 0.5; 
// 設置 圓形布局半徑   
    CGFloat randius = centerY- 30;   
// 獲得每個 cell 之間的間距 (所有 cell 平分了整個圓) 
    CGFloat angelMargin = M_PI * 2 / count;   
// 遍歷進行設置布局  
  for (int i = 0; i < count ; i ++) {       
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
// 創建對應索引的布局
        UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
// 根據三角函數設置布局的中心點
        CGFloat a = sin(i * angelMargin) * randius;
        CGFloat b = cos(i * angelMargin) * randius;
        layoutAtt.center = CGPointMake(centerX + a, b+ centerY);
        layoutAtt.size = CGSizeMake(WH, WH);   
        [layoutAtts addObject:layoutAtt];
    }
    return layoutAtts;
}  
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容