iOS开发:九宫格灵活布局

实现一行不同格子数的九宫格布局。

预览



思路

  • 手动添加UI控件
  • 用除法和求余运算计算格子坐标
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    //parse the json file
    NSString* path = [[NSBundle mainBundle] pathForResource:@"LifeService" ofType:@"json"];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];
    
    NSError *error;
    
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData
                                                 options:NSJSONReadingMutableContainers error:&error];
    
    if (!jsonObj || error)
        NSLog(@"JSON parse failed!");
    
    self.squareData = [jsonObj objectForKey:@"Record"];
    
    //set view background color
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    //setup the square layout
    for(int i = 0; i < square_count; i++)
    {
        //comput the row and col index
        int row = i/col_count;
        int col = i%col_count;
        
        //comput the size and position
        float block_size = (self.view.frame.size.width - block_space*col_count)/col_count;
        float x = block_space/2 + col*(block_size + block_space);
        float y = TOP_MARGIN + block_space/2 + row*(block_size + block_space);
        
//        NSLog(@"%f %f", x, y);
        
        UIView *block = [[UIView alloc] init];
        block.frame = CGRectMake(x, y, block_size, block_size);
        block.backgroundColor = [UIColor whiteColor];
        
        UIButton *button = [[UIButton alloc] init];
        button.frame = CGRectMake(0, 0, block_size, block_size);
        
        //set button image
        [button setImage:[UIImage imageNamed:[self.squareData[i] objectForKey:@"imgLogo"]] forState:UIControlStateNormal];
        
        [button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //set button title
        [button setTitle:[self.squareData[i] objectForKey:@"title"] forState:UIControlStateNormal];
//        [button setBackgroundColor:[UIColor greenColor]];

        [block addSubview:button];
        
        //add the button to the block
        [self.view addSubview:block];
    }
}

源代码下载

csdn: 九宫格
github: SquareLayout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值