objective C 需要帮助

objective C help needed

我正在尝试制作欢呼板,只要我的行数是奇数,它就可以工作。在偶数中,它对整个第二行使用颜色 1,对第一行使用颜色 2。而不是第一个盒子上的颜色 1 和第二个盒子上的颜色 2 来回切换。

这是我绘制矩形(正方形)的逻辑。我认为这有什么问题吗?

PanelWidth 是用户输入的每框像素大小

PanelHeight 是用户输入的每个框的像素大小

i 是列数(水平)

r 是行数(垂直)

// Drawing Rectangles
bool switch1 = true;
for (int i = 0; i < col; i++) {
    long int positionHor = (panelWidth*i);
    for (int r = 0; r < row; r++) {
        int positionVer = (panelHeight*r);
        NSRect col1= NSMakeRect(positionHor,positionVer, panelWidth, panelHeight);
        if (_bgEnable) {
            if(switch1)
            {
                [rectColor set];
            }
            else {
                [rectColor2 set];
            }

        }

        else{
            [[NSColor colorWithCalibratedWhite:0.0 alpha:0.0] setFill];
            NSRectFillUsingOperation(col1, NSCompositeSourceAtop);
        }

        NSRectFill (col1);
        switch1 = !switch1;


        if (_BoarderEnable) {
        [boarderColor set];
        NSFrameRectWithWidth ( col1, _boarderWidth);
        }
    }
}

问题在于您确定绘制颜色的方式

for (int r = 0; r < row; r++) 
{
  …        
  if (_bgEnable) 
  {
    if(switch1)
    {
      …
    }
  }
  …
  switch1 = !switch1;
}

如果您有偶数个矩形,switch 被反转偶数次,在下一行的开头与上一行的开头具有相同的结果。

您应该计算它而不是使用布尔开关:

for (int r = 0; r < row; r++) 
{
  …        
  if (_bgEnable) 
  {
    if( (r+i) % 2 ) // <-- here
    {
      …
    }
  }
  …
}

% 表示 modulo 与第二个参数 2 它是交替的,因为 mod 到 2 是 0, 1, 0, 1, … 在第一列r 为零,因此每一行的颜色都会交替。