同じ方法ですべてのボタンを処理できます。ここでは、(id)sender
が渡される引数値です。次に、(UIButton*)sender
の値を特定のボタンオブジェクト値と(キャストで)比較することによって、ボタン固有の処理を実行できます。この単一のメソッドの中で、最後に押されたボタンである送信者の値が常に得られます。 lastButtonPressed = sender;
アップデートのようvaribleにそれを割り当てます。申し訳ありませんが、ここでは
lastButtonPressed = (UIButton*)sender;
のようにするべきことは、いくつかの詳細は以下のとおりです。
あなたがInterface Builderのを使用している場合は、あなたの中のボタンのハンドラメソッドに各ボタンを接続しますビューコントローラ。 (私はInterface Builderをそれほど使用しませんが、ボタン内部のイベントをボタンハンドラメソッドに接続したいと思います)。
インターフェイスビルダを使用しない場合、ビューコントローラでイールズを初期化する場所にこの行を追加できます。あなたのボタンハンドラがbuttonHandler:
があなたのボタンの一人一人のためにこれを行うと呼ばれていると想定します。あなたのヘッダファイルで
[oneOfYourButtons addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventTouchUpInside];
//... include this for each button ...
[anotherOneOfYourButtons addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventTouchUpInside];
を、(例えば)lastButtonPressed
と呼ばれるインスタンス変数を作成します。他のivarsを初期化した実装ファイルでは、これをnilに初期化します。
- (void)buttonHandler:(UIButton*)sender{
if (sender == button1) {
//... do things for button1
// what you do here may depend on the value of lastButtonPressed, like this, for example
if (lastButtonPressed == someButton) {
//... do something
//... you may want to reset the value of lastButtonPressed
lastButtonPressed = nil;
}
else if (sender == button2) {
//... do things for button2
}
else if (sender == button3) {
//... do things for button3
}
else
//... Repeat for all the buttons you want to handle. The compiler will optimize this so don't worry about that
//...
// probably at the end, you want to save the current button as the last button pressed
lastButtonPressed = sender;
}
出典
2011-12-08 23:15:36
Jim
もう少し詳しく方法可能性のチャンス:
次に、このようにメソッドを追加しますか?私はそれを設定しようとしているが運がない。 –
ありがとうございました。私はちょうどあなたの最初の応答に基づいて解決策を考え終わった、私はあなたが作った編集を通してまだ見ていない。私はUIButton * lastOpPressedに@propertyを追加し、最後にlastOpPressed ==(UIButton *)の送信者を入れ、[self lastOperatorPressed nameOfOperatorButton]を追加した演算子のIBActionに ' - (void)lastOperatorPressed(id)sender' if文を私の明確なメソッドに追加すると、うまくいきます!私は十分にあなたに感謝できません! –
私はそれがうまくいってうれしいです。 – Jim