我是 Obj-C
的新手。
我有以下棋盘:
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
CGRect square = {horizontalOffSet + (column * squareSize),
verticalOffSet + (row * squareSize),
squareSize, squareSize};
UIView *rect = [[UIView alloc] initWithFrame:square];
rect.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
horizontalOffSet = horizontalOffSet + squareSize;
if ((row + column) % 2 == 0) {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor whiteColor];
[anotherRect addSubview:rect];
} else {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor blackColor];
[anotherRect addSubview:rect];
}
}
}
我的任务是在旋转时更改字段的颜色,例如,在向左旋转时用青色和紫色填充它。不清楚如何去做。
最佳答案
@somerk 检查我更新的代码:
1) 我已将标识符 (tag
) 指定为已识别的国际象棋 View ,其中白色和黑色。你可以在没有标识符的情况下做到这一点,但如果有多个 subviews
标识符是更好的获取方式。
int horizontalOffSet = 2;
int squareSize = 40;
int verticalOffSet = 2;
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
CGRect square = {horizontalOffSet + (column * squareSize),
verticalOffSet + (row * squareSize),
squareSize, squareSize};
UIView *rect = [[UIView alloc] initWithFrame:square];
rect.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
horizontalOffSet = horizontalOffSet + squareSize;
if ((row + column) % 2 == 0) {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.tag = 101;
rect.backgroundColor = [UIColor whiteColor];
[self.view addSubview:rect];
} else {
//verticalOffSet = verticalOffSet + squareSize;
rect.tag = 102;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor blackColor];
[self.view addSubview:rect];
}
}
2) 我已经在 UIButton
单击上执行了颜色更改事件,因此您必须在旋转事件后使用该代码。
-(IBAction)changeColor:(UIButton *)btn{
for(UIView *rectViews in self.view.subviews){
UIColor *clrblck = [UIColor blackColor];
if(rectViews.backgroundColor == clrblck && rectViews.tag == 102){
rectViews.backgroundColor = [UIColor cyanColor];
}else if(rectViews.backgroundColor == clrblck && rectViews.tag == 101){
rectViews.backgroundColor = [UIColor purpleColor];
}else{
// you will get other views here..
}
}
}
- 我已获取所有 subview 并检查
backgroundColor
和tag
并更改其backgroundColor
。
注意:根据您在 loop
中的 View 名称以及您在 中将
。rect
添加为 subviews
的位置更改 View 名称>另一个矩形
有问题可以随时问我。快乐编码:)
关于ios - 旋转后改变棋盘颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55375910/