程序员iOS进阶指南iOS Developer

九宫格计算

2016-03-09  本文已影响457人  飞翔的道长
- (void)add
{
    
    //定义容器的宽
    CGFloat shopW = 50;
    //定义容器的高
    CGFloat shopH = 70;
    //指定列数
    int clos = 3;
    //计算列间距(整体宽度减掉列数乘以单个容器的宽度再除以列数减一)
    CGFloat cloMargin = (self.shopsView.frame.size.width - clos * shopW) / (clos - 1);
    //行间距
    CGFloat rowMargin = 10;
    //索引
    NSUInteger index = self.shopsView.subviews.count;
    //列数(取模)
    NSInteger col = index % clos;
    //x坐标值(当前列数乘以容器的宽加列间距)
    CGFloat shopX = col * (shopW + cloMargin);
    
    //行数(取商)
    NSInteger row = index / clos;
    //y坐标值(当前列数乘以容器的高加行间距)
    CGFloat shopY = row * (shopH + rowMargin);
    
    UIView *shopView = [[UIView alloc] init];
    shopView.backgroundColor = [UIColor redColor];
    
    // 添加图片
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage imageNamed:@"danjianbao"];
    iconView.frame = CGRectMake(0, 0, 50, 50);
    [shopView addSubview:iconView];
    
    // 添加文字
    UILabel *label = [[UILabel alloc] init];
    label.text = @"单肩包";
    label.frame = CGRectMake(0, 50, 50, 20);
    label.font = [UIFont systemFontOfSize:11];
    label.textAlignment = NSTextAlignmentCenter;
    [shopView addSubview:label];
    
    shopView.frame = CGRectMake(shopX, shopY, shopW, shopH);
    [self.shopsView addSubview:shopView];
}

上一篇下一篇

猜你喜欢

热点阅读