我需要更改UIButtons矩阵上的图像,而我唯一知道的解决按钮的方法就是标记。但我找不到一种方法来实际使用这个标识符。 这些按钮是在viewDidLoad期间以编程方式创建的。
以下是创建按钮的代码:
#define N_ROWS 4
#define N_COLS 3
int N_IMG = 0;
for (int a = 0; a < N_COLS; a++) {
for (int j = 0; j < N_ROWS; j++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(a * 65.0 + 25, j * 65.0 + 15, 10.0, 10.0);
aButton.tag = j + a * N_ROWS + 1;
[aButton setBackgroundColor:[UIColor redColor]];
N_IMG = N_IMG++;
[self.view addSubview:aButton];
number_sorted = 1;
}
}
以下是设置图片的代码:
- (IBAction)set_image:(id)sender {
#define N_ROWS 4
#define N_COLS 3
int N_IMG = 0;
for (int a = 0; a < N_COLS; a++) {
for (int j = 0; j < N_ROWS; j++) {
uibutton aButton.tag == (j + a * N_ROWS + 1)
setImage:[UIImage imageNamed:[puzzles objectAtIndex:N_IMG]]
forState:UIControlStateNormal];
N_IMG = N_IMG++;
}
}
}
这是truble开始的代码: uibutton aButton.tag ==(j + a * N_ROWS + 1)
我可以将其设置为工作吗?
答案 0 :(得分:8)
简答:
RE:“如何使用代码访问UIButton ......”
UIButton *tmpButton = (UIButton *)[self.view viewWithTag:tmpTag];
RE:“......并更改其图片?”
[tmpButton setImage:[UIImage imageNamed:@"MyGreatImage.png"] forState:UIControlStateNormal];
长答案:
RE:*“这是truble开始的代码:uibutton aButton.tag ==(j + a * N_ROWS + 1)”*
是的,我可以看到麻烦。您使用的行是设置按钮的标记,而不是从标记中获取按钮。
要从已知标签获取按钮,请执行以下操作:
// define the tag index
int tmpTag = 123;//replace "123" with your own logic, i.e. (j + a * N_ROWS + 1)
// get the button with the given tag
UIButton *tmpButton = (UIButton *)[self.view viewWithTag:tmpTag];
// assign the image
tmpImage = [UIImage imageNamed:@"MyGreatImage.png"];
[tmpButton setImage:tmpImage forState:UIControlStateNormal];
奖励代码:在此阶段,您还可以添加或删除与按钮相关的操作。
//Remove all actions associated the button
[aButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
//Assign a new button action: using the exact selector name ("myMethodName")
[aButton addTarget:self action:@selector(myMethodName:) forControlEvents:UIControlEventTouchUpInside];
//Assign a new button action: using a calculated selector name
//(suppose I have a bunch of methods with the prefix "myNumberedMethodName_" followed by an index.
int tmpSomeNumber = 12;
SEL tmpSelector = NSSelectorFromString ([NSString stringWithFormat:@"myNumberedMethodName_%i:",tmpSomeNumber);
// don't forget to include the ":" symbol in the selector name
[aButton addTarget:self action:tmpSelector forControlEvents:UIControlEventTouchUpInside];
注意:“viewWithTag”通常会返回一个View对象。 Button是一种特殊类型的View,具有特殊属性,如image。因此,为了让它返回一个Button对象而不是更通用的View对象,我们通过在定义中使用(UIButton *)将它作为Button来初始化它。
但如果你想要的只是改变按钮的不透明度,那么你就不必将它作为按钮投射。您只需将其初始化为通用视图:
// set opacity of a button
float tmpOpacity = 0.5;//half-visible
UIView *tmpView = [self.view viewWithTag:tmpTag];//get the view object associated with button's tag (remember, a button IS a view)
[[tmpView layer] setOpacity:tmpOpacity];
答案 1 :(得分:4)
我真的不明白你想要做什么,但为什么你不能存储你的UIButton对象(即在NSArray对象中),所以你可以稍后访问它们(在你的第二个循环中)?