I want to make 11 buttons specified below order with 2 for loops, it is a matrix but for 11 buttons.
for (int i = 1; i <= 2; i++) {
for (int k = 1; k <= 6; k++) {
j++;
NSString *key = [NSString stringWithFormat:@"Color%d",j];
UIColor *color = [dict objectForKey:key];
ColorBtn *colorBtn = [UIButton buttonWit开发者_如何学GohType:UIButtonTypeCustom];
colorBtn.frame = CGRectMake(4+(startPointX*k), 320+(startPointY*i), 38, 37);
colorBtn.backgroundColor = color;
colorBtn.tag = j;
[colorBtn setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[colorBtn addTarget:self action:@selector(SetUIColor:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:colorBtn];
}
}
[][][][][][]
[][][][][]
Simply add a few lines to your inner for
loop towards the top:
...
j++;
// Add these lines
if (i == 2 && k == 6) {
continue;
}
// Add these lines
NSString *key = [NSString stringWithFormat:@"Color%d",j];
...
This will ensure that the final column in the second row is skipped.
Another alternative is to check the value of j
- this would allow you to change the dimensions of your matrix while still ensuring only 11 entries are created in total:
...
j++;
// Add these lines
// I'm assuming that j is 1-based, not 0-based
if (j > 11) {
break;
}
// Add these lines
NSString *key = [NSString stringWithFormat:@"Color%d",j];
...
for (int i = 1; i <= 2; i++) {
for (int k = 1; k <= 6; k++) {
j++; if(j<12) { //Your code for creating buttons.
}
} }
for j=0(at starting).
精彩评论