如何在IBAction方法中构造if-else语句

时间:2009-07-14 06:17:11

标签: objective-c syntax if-statement

我不知道如何在IBAction中制作if-else语句!我只能在按钮点击中制作它们...我想要它做的是检查int问题所在的#并进行适当的更改。请帮忙!

MainView.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface MainView : UIView{
    IBOutlet UIImageView *background;
    IBOutlet UIButton *button1;
    IBOutlet UIButton *button2;
    IBOutlet UIButton *button3;
    IBOutlet UIButton *button4;
    IBOutlet UILabel *questionLabel;
}

@property (nonatomic, retain) UIButton *button1;
@property (nonatomic, retain) UIButton *button2;
@property (nonatomic, retain) UIButton *button3;
@property (nonatomic, retain) UIButton *button4;
@property (nonatomic, retain) UILabel *questionLabel;
@property (nonatomic, retain) UIImageView *background;

- (IBAction)Button1clicked;
- (IBAction)Button2clicked;
- (IBAction)Button3clicked;
- (IBAction)Button4clicked;
@end

MainView.m

    #import "MainView.h"

    @implementation MainView

    @synthesize button1, button2, button3, button4, questionLabel, background;

    int question = 1;

    BOOL oneRight = FALSE;
    BOOL twoRight = FALSE;
    BOOL threeRight = FALSE;
    BOOL fourRight = FALSE;


    - (IBAction)Button1clicked {
        if (oneRight == TRUE) {
            questionLabel.text = @"CORRECT!";
            question++;
        } else {
            questionLabel.text = @"FAIL";   
        }
    }

    - (IBAction)Button2clicked {
        if (twoRight == TRUE) {
            questionLabel.text = @"CORRECT!";
            question++;
        } else {
            questionLabel.text = @"FAIL";   
        }
    }

    - (IBAction)Button3clicked {
        if (threeRight == TRUE) {
            questionLabel.text = @"CORRECT!";
            question++;
        } else {
            questionLabel.text = @"FAIL";   
        }
    }

    - (IBAction)Button4clicked {
        if (fourRight == TRUE) {
            questionLabel.text = @"CORRECT!";
            question++;
        } else {
            questionLabel.text = @"FAIL";   
        }
    }

    int foo(int question) {
        if (question == 1) {
        oneRight = TRUE;
        twoRight = FALSE;
        threeRight = FALSE;
        fourRight = FALSE;
        }
    }

    @end

2 个答案:

答案 0 :(得分:2)

我建议使用IBAction调用的sender参数。每次调用IBAction方法时,调用的对象都会随之发送,从而可以轻松确定单击了哪个按钮。

- ( IBAction ) buttonClicked:( id ) sender {

   if( [ sender tag ] == answer ) {
      questionLabel.text = @"CORRECT";
      ...
   } 
   else {

      questionLabel.text = @"FAIL";
      ...
   }
}

答案 1 :(得分:1)

根据Beginning iPhone Development,您还可以将发件人与按钮的指针进行比较

-(IBAction)buttonPressed:(id) sender {
     if (sender == firstPointer ) {    
          ...
     }
     else if (sender == secondPointer ) {    
          ...
     }
     ...
 }