边开发边学习iOS项目实践中的学习

ios九宫格布局

2017-06-26  本文已影响64人  coderhlt

一、按钮实现

#import "ViewController.h"
static NSInteger const corlmax = 4;
static CGFloat const margin = 20;
#define itemWH ([UIScreen mainScreen].bounds.size.width-(corlmax - 1) * margin) / corlmax
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    for (int i = 0; i < 10; i++) {
        int row=i/corlmax;//所在行
        int col=i%corlmax;//所在列
        //创建按钮
        UIButton *btn= [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor=[UIColor redColor];
        CGFloat x= (itemWH+margin)*col;
        CGFloat y =(itemWH+margin)*row;
        btn.frame=CGRectMake(x, y, itemWH,  itemWH);
        [self.view addSubview:btn];
    }
}

二、UICollectionview实现

#import "ViewController.h"
static NSInteger const cols = 4;
static CGFloat const margin = 10;
#define itemWH ([UIScreen mainScreen].bounds.size.width - 20-(cols - 1) * margin) / cols
static NSString * const ID = @"cell";
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置item尺寸
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    layout.minimumInteritemSpacing = margin;
    layout.minimumLineSpacing = margin;
    // 创建UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375, 667) collectionViewLayout:layout];
    [self.view addSubview:collectionView];
    collectionView.backgroundColor=[UIColor whiteColor];
    _collectionView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate=self;
    collectionView.scrollEnabled = NO;
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 从缓存池取
 UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.backgroundColor=[UIColor redColor];
    return cell;
}

三、补充:根据item的个数动态确定collectionview高度

      collectionView高度 = rows * itemWH

     1.确定item的个数
      NSInteger count = _squareItems.count;

     2.获得collectionview的总行数
      NSInteger rows = (count - 1) / cols + 1;
        // Rows = (count - 1) / cols + 1,collectionview万能公式计算总行数
  
      3.// 设置collectioView高度
       self.collectionView.frame=CGRectMake(0, 0, 375, rows*itemWH);
        ```
上一篇 下一篇

猜你喜欢

热点阅读