iOS枚举类型的定义和使用
枚举的定义
ViewController895.h
#import <UIKit/UIKit.h> @interface ViewController895 : UIViewController //定义枚举类型 typedef enum { ENUM_ViewController895_ActionTypeStart=0,//开始 ENUM_ViewController895_ActionTypeStop,//停止 ENUM_ViewController895_ActionTypePause//暂停 } ENUM_ViewController895_ActionType; //-------in parameters--------------- @property (nonatomic,assign) NSInteger InActionType; //操作类型 @end
上面我们就在ViewController895.h定义了一个枚举类型,枚举类型的值默认是连续的自然数,例如例子中的
ENUM_ViewController895_ActionTypeStart=0,//开始
那么其后的就依次为1,2,3....所以一般只需要设置枚举中第一个的值就可以。
枚举的使用
在需要使用的地方,引入枚举定义所在的.h文件,例如现在要在ViewController896.h中使用上面定义的枚举,那么:
ViewController896.h
#import <UIKit/UIKit.h> #import "ViewController895.h" @interface ViewController896 : UIViewController @end
将枚举定义的.h import进来
然后就可以使用了。
ViewController896.m
#import "ViewController896.h" @interface ViewController896 () @end @implementation ViewController896 - (void)viewDidLoad { [super viewDidLoad]; self.edgesForExtendedLayout=UIRectEdgeNone; self.view.backgroundColor=[UIColor whiteColor]; UIButton* btnGo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btnGo setTitle:@"GO" forState:UIControlStateNormal]; [btnGo setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; btnGo.frame = CGRectMake(20, 120, 100, 40); btnGo.backgroundColor=[UIColor whiteColor]; btnGo.layer.borderWidth=0.5; btnGo.layer.borderColor=[UIColor blueColor].CGColor; [btnGo addTarget:self action:@selector(_doClickGo:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btnGo]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(void) _doClickGo : (UIButton*) sender { ViewController895* nextpage = [[ViewController895 alloc]init]; nextpage.InActionType=ENUM_ViewController895_ActionTypePause; [self.navigationController pushViewController:nextpage animated:YES]; }
代码中的:
nextpage.InActionType=ENUM_ViewController895_ActionTypePause;
就直接使用了之前定义的枚举类型数据:ENUM_ViewController895_ActionTypePause ,其值为2.