摘自:http://coffeeandsandwich.com/?p=8

在 iOS 6 和 Mac OS X 10.8 以前,定义枚举类型的方式如下:

 
typedef enum the_enum_name{
    value_1,
    value_2,
    value_3
}the_enum_type_name;

 

注意:
1.  the_enum_name 和 the_enum_type_name 可以是一样的。
2. 你甚至可以不写 the_enum_name,只写 the_enum_type_name。

从iOS6和Mac OS X 10.8开始,苹果允许你使用新的方式来定义枚举类型

 
typedef NS_ENUM(NSInteger, the_enum_type_name){
    value_1,
    value_2,
    value_3
};

 

NS_ENUM 的第一个参数用来声明枚举值们所属的类型,只能是整形数值类型,一般都是用NSInteger就可以了。第二个参数是枚举类型的名字。

那么这两者有什么差别呢?实际上差别不大,不过后者更直观,而且 NS_ENUM 第二个参数则直接取代了前者的 the_enum_name 和 the_enum_type_name。

另外,枚举类型还能进行位运算。你可以使用 | 进行或运算或者 & 进行与运算。不过需要用 UIViewAutoresizing  的枚举类型,它的定义就是下面这样子的:

 
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
    UIViewAutoresizingFlexibleWidth = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin = 1 << 3,
    UIViewAutoresizingFlexibleHeight = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};

 

这个枚举类型是用来指定当控件的容器(比如说窗口)的大小发生变化时,控件的大小和位置应当如何变化,如果希望这个控件的宽度不变,只改变左右边距,那么可以这样负值:

 
someButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

 

 

参考:

What is a typedef enum in Objective-C?
http://stackoverflow.com/questions/707512/what-is-a-typedef-enum-in-objective-c

NS_ENUM & NS_OPTIONS
http://nshipster.com/ns_enum-ns_options/

 

相关文章:

  • 2019-11-02
  • 2021-05-30
  • 2021-06-23
  • 2021-08-10
  • 2021-09-30
猜你喜欢
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
  • 2022-03-02
  • 2021-10-30
  • 2020-05-02
相关资源
相似解决方案