0

我正在使用它来定义按钮网格。我想以编程方式更改特定按钮的属性,例如:

if(button.tag == 6)
{
    [button setBackgroundImage:imageRed forState:UIControlStateNormal];
    [button setImage:imageRed forState:UIControlStateNormal];
}

下面的按钮创建。


for (int y=0; y < 3; y++) {
    for (int x = 0; x < 3; x++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        //button.frame = CGRectMake(40 + 80 * x, 40 + 80 * y, 80, 80);

        button.frame=CGRectMake(5+5*x,5+5*y,5,5);

        unsigned buttonNumber = y * 3 + x + 1;
        button.tag = buttonNumber;
        //[button setTitle:[NSString stringWithFormat:@"%u", buttonNumber] forState:UIControlStateNormal];
        [button setBackgroundImage:imageWhite forState:UIControlStateNormal];
        [button setImage:imageWhite forState:UIControlStateNormal];

        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview: button];
    }
}
4

2 回答 2

1

我不完全确定您的问题是什么,但似乎“如何找到具有特定标签的视图?”。答案是 UIView 方法

- (UIView *)viewWithTag:(NSInteger)tag

这将查看当前视图及其指定标签的所有子视图,并返回它找到的第一个与其匹配的视图。例如,要获取标签为 6 的按钮,只需执行以下操作:

UIView* button = [self.view viewWithTag:6];

当然,在处理目标方法时,比如你的buttonPressed:方法,触发事件的视图作为参数传递,所以如果这是你唯一需要的时候,你也可以使用它。除此之外,您的代码中的所有内容看起来都很好。

于 2012-09-23T02:59:05.823 回答
0

我最终使用了这个...

 for (int row = 0; row < ROWS; row++) {
    for (int col = 0; col < COLS; col++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       // [ButtonArray addObject:button];

        button.tag = row * COLS + col;

        button.frame = CGRectMake(5+5*row,5+5*col,5,5);
        [button addTarget:self action:@selector(didPushButton:) forControlEvents:UIControlEventTouchDown];

        [button setBackgroundImage:imageWhite forState:UIControlStateNormal];
        [button setImage:imageWhite forState:UIControlStateNormal];
        [self.view addSubview:button];
        buttonArr[row*COLS+col]=button;
    }
}
于 2012-09-23T19:39:14.450 回答