如何在矩阵中制作11个按钮

时间:2021-06-21 20:21:41

I want to make 11 buttons specified below order with 2 for loops, it is a matrix but for 11 buttons.

我想在下面指定11个按钮,2个循环,它是一个矩阵,但是11个按钮。

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 buttonWithType: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];
  }
 }

[][][][][][]
[][][][][]

2 个解决方案

#1


1  

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的值 - 这将允许您更改矩阵的尺寸,同时仍然确保总共只创建了11个条目:

...
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];
...

#2


0  

for (int i = 1; i <= 2; i++) {

for(int i = 1; i <= 2; i ++){

for (int k = 1; k <= 6; k++) {

for(int k = 1; k <= 6; k ++){

j++; if(j<12) { //Your code for creating buttons.

J ++; if(j <12){//您创建按钮的代码。

       }

} }

for j=0(at starting).

对于j = 0(在开始时)。

#1


1  

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的值 - 这将允许您更改矩阵的尺寸,同时仍然确保总共只创建了11个条目:

...
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];
...

#2


0  

for (int i = 1; i <= 2; i++) {

for(int i = 1; i <= 2; i ++){

for (int k = 1; k <= 6; k++) {

for(int k = 1; k <= 6; k ++){

j++; if(j<12) { //Your code for creating buttons.

J ++; if(j <12){//您创建按钮的代码。

       }

} }

for j=0(at starting).

对于j = 0(在开始时)。