【问题标题】:How to add enum as datasource in uipickerview?如何在 uipickerview 中添加枚举作为数据源?
【发布时间】:2012-07-31 12:01:02
【问题描述】:

我在 ApplicationConstants.h 文件中创建了一个枚举,枚举如下。

typedef 枚举 { 当前位置 = 0, 当前城市, CurrentRegion } 枚举位置;

现在的问题是我不知道如何在UIPickerView 中将此枚举设置为数据源!谁能给我这个想法?我以前使用NSArray 作为数据源。但我现在想要枚举。因为这个问题,我卡住了。你能帮助我吗 ?这样我就可以继续申请了。

【问题讨论】:

    标签: objective-c ios enums xcode4.2 uipickerview


    【解决方案1】:

    您不能直接显示枚举的标识符。您必须准备一个大的 if/else/switch 块来为每个元素准备一个字符串,或者为数组中的每个元素添加字符串并从那里按索引选择。

    在程序中通常使用枚举类型而不是幻数,因此旨在使代码更容易被人类阅读,但底层表示是一种基本数据类型(int、char 等)。

    【讨论】:

    • 我不同意你的第一句话,因为你可以
    【解决方案2】:

    对于 UIPickerViewDataSource

    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
            return LOCATION_COUNT;
    }
    

    使用枚举计数技巧

    typedef enum { CurrentLocation = 0, CurrentCity, CurrentRegion, LOCATION_COUNT} enumLocation;
    

    对于 UIPickerViewDelegate

    - (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
         [self.enumLocationStringDict objectForKey:[NSNumber numberWithInt:row]]
    }
    

    字典可以如下

    self.enumLocationStringDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"CurrentLocation", [NSNumber numberWithInt:CurrentLocation],
                                  @"CurrentCity", [NSNumber numberWithInt:CurrentCity],
                                  @"CurrentRegion", [NSNumber numberWithInt:CurrentRegion],
                                  ,nil];
    

    【讨论】:

      【解决方案3】:

      您可以选择为它定义一个简单宏的方式,例如:

      在头文件(.h)中:

      #define NAMEOF(var) @#var
      
      typedef enum : NSInteger {
          CustomTypeUknown = 0,
          CustomTypeSomething,
          CustomTypeParticularValue,
          CustomTypeBoringValue,
      } CustomType;
      

      在实施文件中 (.m)

      NSArray *_array = [NSArray arrayWithObjects:NAMEOF(CustomTypeUknown), NAMEOF(CustomTypeSomething), NAMEOF(CustomTypeParticularValue), NAMEOF(CustomTypeBoringValue), nil];
      

      对象将是带有名称的字符串,但为了安全起见,您可以通过记录 _array 来检查值:

      NSLog(@"%@", _array);
      

      应该是这样的:

      (
          CustomTypeUknown,
          CustomTypeSomething,
          CustomTypeParticularValue,
          CustomTypeBoringValue
      )
      

      如果我没有误解你的问题,那就是你在找...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 2010-12-26
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多