制作简单的九宫格:
源码如下:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //创建九宫格
NSInteger col = ; //每行几列
NSInteger total = ;//总个数 //格子的宽度、高度
UIImage *image = [UIImage imageNamed:@"0.png"];
CGFloat cellWidth = image.size.width;
CGFloat cellHeight = image.size.height; CGFloat screenWidth = self.view.frame.size.width; CGFloat gapX = (screenWidth-cellWidth*col)/(col+);//x方向的间隔
CGFloat gapY = gapX;//y方向的间隔 //计算行数
NSInteger row = ; for(int i=; i<total; i++)
{
UIButton *button = [[UIButton alloc]init];
[button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]] forState:UIControlStateNormal]; //计算是否需要换行
if(i%col == )
{
row++;
}
CGFloat x = gapX+(cellWidth+gapX)*(i%col);
CGFloat y = gapY+(cellHeight+gapY)*row;
button.frame = CGRectMake(x, y, cellWidth, cellHeight); [self.view addSubview:button];
}
} @end