iOS开发小TipsiOS基础

ios九宫格布局

2020-11-20  本文已影响0人  冷武橘

一、item宽度相等

1.1、按钮实现

#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];
    }
}

1.2、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;
}

1.3、补充:根据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);

二、item宽度不相等

2.1、标签实现

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
   CGFloat linemargin = 15;
   CGFloat itemmargin = 10;
   CGFloat y = 50;
    NSArray *arr = @[@"测试",@"测试测试",@"ceshiceshiceshi",@"cccc",@"dddffkkkkf",@"2344",@"rrrrr",@"ffffffffffff",@"0000",@"lopp[[[eoeoeeoro"];
    CGRect lastFrame = CGRectZero;
 
    for (int i=0; i<10; i++) {
        UILabel *lable = [[UILabel alloc]init];
        lable.text = arr[i];
        lable.font = [UIFont systemFontOfSize:18];
        CGFloat width = [self getWidthWithText:arr[i] height:40 font:18];
        lable.backgroundColor = [UIColor redColor];
        [self.view addSubview:lable];
        if (i==0) {
            lable.text = arr[i];
            lable.frame = CGRectMake(0, y, width, 40);
        }else{
            CGFloat x = CGRectGetMaxX(lastFrame) + itemmargin;
            if (x+width>[UIScreen mainScreen].bounds.size.width) {
                x = 0;
                
                y =  CGRectGetMaxY(lastFrame)+linemargin;
            }
            
            lable.frame = CGRectMake(x, y, width, 40);
            
        }
        lastFrame = lable.frame;
    }
}

//根据高度度求宽度  text 计算的内容  Height 计算的高度 font字体大小
-(CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font{
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                        context:nil];
    return rect.size.width;
}

2.2、collectionFlowout布局

   flowout.estimatedItemSize = CGSizeMake(40, 40);
    flowout.itemSize  =      UICollectionViewFlowLayoutAutomaticSize;
    flowout.minimumLineSpacing = 10;
    flowout.minimumInteritemSpacing =10;


-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
   NSMutableArray *attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    CGFloat y = 0;
    for (int i=0; i<attributes.count; i++) {
        if (i>0) {
            UICollectionViewLayoutAttributes *attr = attributes[i];
            CGRect frame = attr.frame;
            UICollectionViewLayoutAttributes *preattr = attributes[i-1];
            CGFloat x = CGRectGetMaxX(preattr.frame)+self.minimumInteritemSpacing;
            if (x+attr.frame.size.width>self.collectionView.frame.size.width) {
                x = 0;
                y = CGRectGetMaxY(preattr.frame) + self.minimumLineSpacing;
            }
            frame.origin.x = x;
            frame.origin.y = y;
            attr.frame = frame;
        }
    }
    return  attributes;
}

完整代码链接: https://github.com/15216838624/collectionView.git

上一篇下一篇

猜你喜欢

热点阅读