2012-03-30 5 views
0

次のコードでは、あるボタンをタッチしてそのボタンの周りに境界線を描画し、他のすべてのボタンに境界線がないことを確認します(合計8つのボタン)。これは、AnswerButtonsと呼ばれるシングルトンクラスのメソッドです。このコードは正常に動作します。ワンオフコードをメソッドに変換する

ここでは、このコードを8つのボタンすべてに使用する必要があるので、変更するボタン番号(pos)を1つの引数で指定する必要があります。ほぼ同じコードである私が入れシングルトンクラス.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。

答えて

1

あなたは、タッチされたボタンである送信者の-activateAnswerAtPos:に電話をかけています。代わりに-activateAnswerAtPos:メソッドを定義するクラスのインスタンスで呼び出す必要があります。それはそれが何であるかを、あなたのコードからは明らかではないのですが、私の推測では、自己である:

[self activateAnswerAtPos:0]; 
+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 
     } 
    } 
} 
のようにひとつの方法に、すべてのボタンアクションを送信します
+0

Paulに感謝します。私の問題はあなたが書いていた時代に解決されましたが、あなたのコードは、私がやっていたことよりもいくつかのことを行うよりはるかに希少な方法を示しています。 –

関連する問題