单层,双层for循环

//单层for循环实现九宫格

- (void)creatNinePatch {

NSArray *array = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I"];

//单层for循环实现九宫格

for (int i = 0; i < 9; i ++) {

UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((Width - (3 * 60 +20))/2.0+(60+10)*(i%3),(Height-(3*60+20))/2.0+(60+10)*(i/3),60,60)];

btn.backgroundColor = [UIColor purpleColor];

//取出数组内容

NSString *title = array[i];

btn.layer.cornerRadius = 20;

//超出父视图之外的部分不显示

btn.layer.masksToBounds = YES;

[btn setTitle:title forState:UIControlStateNormal];

[self.view addSubview:btn];

}


//双层for九宫格按钮添加页面

- (void)creatNinePatch {

NSArray *str= @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I"];

for(int i=0; i<3; i++) {

for(int j=0; j<3; j++) {

UIButton *button=[[UIButton alloc] initWithFrame:CGRectMake(j*100+20, i*60+100, 80, 40)];

button.backgroundColor=[UIColor redColor];

[button setTitle:str[i*3+i] forState:UIControlStateNormal];

[self.view addSubview:button];

button.tag=i*3+j+1;

[button addTarget:self action:@selector(backWithTag:) forControlEvents:UIControlEventTouchUpInside];

- (void)backWithTag:(UIButton*)button {

if(button.tag==1) {

[self back];

}

if(button.tag==2) {

[self next];

}

if(button.tag== 3 ) {

[self back];

}

}

name= @[@"�",@"�",@"�",@"�",@"�",@"�",@"�",@"�",@"�",@"�",@"�",@"�"];

// NSArray *background = @[@"sx0.png",@"sx1.png",@"sx2.png",@"sx3.png",@"sx4.png",@"sx5.png",@"sx6.png",@"sx7.png",@"sx8.png",@"sx9.png",@"sx10.png",@"sx11.png"];

NSMutableArray *background = [NSMutableArray arrayWithCapacity:0];

for(inti = 0; i < 12; i ++) {

UIImage *picture = [[UIImage alloc] init];

picture = [UIImage imageNamed:[NSString stringWithFormat:@"sx%d.png",i]];

[background addObject:picture];

}




//单层for循环实现九宫格

for(inti = 0; i < 12; i ++) {

//第一为行(20+(60+10)*(i%3) 20为定点(60+10)宽加边距

%取余数

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20+(60+10)*(i%3),30+(60+10)*(i/3),60,60)];

//取出数组内容

NSString *title =name[i];

[btn setTitle:titleforState:UIControlStateNormal];

//取出数组里的图片

UIImage*picture = background[i];

[btn setBackgroundImage:picture forState:UIControlStateNormal];

btn.layer.cornerRadius= 30;

//超出父视图之外的部分不显示

btn.layer.masksToBounds=YES;

//绑定方法

[btn addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];

btn.tag= i + 100;

[view1 addSubview:btn];

}

}

你可能感兴趣的:(单层,双层for循环)