我有以下代码,触摸一个按钮并在该按钮周围绘制边框,然后确保所有其他按钮没有边框(总共8个按钮)。这是一个名为AnswerButtons的单例类中的方法。这段代码工作正常。
- (IBAction)button1WasTouched:(id)sender {
NSLog(@"Hello from button 1");
// retrieve, modify and update clueAnsState
NSMutableArray *newCAS = [[GameData gameData].curData objectForKey:@"clueAnsState"];
[newCAS replaceObjectAtIndex:0
withObject:@"2"];
[[GameData gameData].curData setObject:newCAS
forKey:@"clueAnsState"];
// Highlight the pressed button & make sure other buttons are not highlighted
for (NSInteger idx = 0; idx < 8; idx++) {
NSString *temp = [newCAS objectAtIndex:idx];
if ([temp isEqualToString:@"1"]) {
UIButton *b = [[AnswerButtons answerButtons].buttons objectAtIndex:idx];
[[b layer] setBorderWidth:0.0f];
}
if ([temp isEqualToString:@"2"]) {
UIButton *b = [[AnswerButtons answerButtons].buttons objectAtIndex:idx];
[[b layer] setBorderWidth:2.0f];
}
}
}
现在,我需要将这个代码用于所有8个按钮,所以我应该编写一个带有一个参数的方法,即要修改的按钮编号(pos)。在单例类.m中我放的几乎是相同的代码:
- (void)activateAnswerAtPos:(int)pos {
// retrieve, modify and update clueAnsState
NSMutableArray *newCAS = [[GameData gameData].curData objectForKey:@"clueAnsState"];
[newCAS replaceObjectAtIndex:pos
withObject:@"2"];
[[GameData gameData].curData setObject:newCAS
forKey:@"clueAnsState"];
NSLog(@"%@", newCAS);
for (NSInteger idx = 0; idx < 8; idx++) {
NSString *temp = [newCAS objectAtIndex:idx];
if ([temp isEqualToString:@"1"]) {
UIButton *b = [[AnswerButtons answerButtons].buttons objectAtIndex:idx];
[[b layer] setBorderWidth:0.0f];
}
if ([temp isEqualToString:@"2"]) {
UIButton *b = [[AnswerButtons answerButtons].buttons objectAtIndex:idx];
[[b layer] setBorderWidth:2.0f];
}
}
}
所以我改变了第一个代码块,使其成为对新方法的调用:
- (IBAction)button1WasTouched:(id)sender {
NSLog(@"Hello from button 1");
[sender activateAnswerAtPos:0];
}
不幸的是,当我得到以下异常时,我做错了什么:
2012-03-30 19:41:40.199 P3[6751:f803] Hello from button 1
2012-03-30 19:41:40.201 P3[6751:f803] -[UIRoundedRectButton activateAnswerAtPos:]: unrecognized selector sent to instance 0x6e709f0
我不确定这里发生了什么;有几种选择也不起作用,我认为我的故障排除方式让我走错了方向。我称之为这种方法的方式有什么问题?显然,我甚至没有开始运行该方法。 TIA。
答案 0 :(得分:2)
很难理解你想要做的事情,但我可能会将所有按钮动作发送到这样一个方法
- (void)buttonTapped:(UIButton *)buttonTapped;
{
NSArray *buttons = [AnswerButtons answerButtons].buttons;
// some kind of switch statement of logic to perform options depending on which button
// Can use the following to get the index
// NSInteger buttonIndex = [buttons indexOfObject:buttonTapped]
for (UIButton *button in buttons) {
if (button == buttonTapped) {
// highlight
} else {
// remove highlight
}
}
}
答案 1 :(得分:1)
您在发件人上拨打-activateAnswerAtPos:
,这是被触摸的按钮。您应该在定义-activateAnswerAtPos:
方法的类的实例上调用它。从你的代码中不清楚这是什么,但我的猜测是自我:
[self activateAnswerAtPos:0];