PickerView具有大量数值

时间:2014-04-21 03:16:47

标签: ios objective-c

我已经看过使用选择器视图的示例,其中选择器的值被硬编码到源代码中,如下所示

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString * title = nil;
 switch(row) {
            case 0:
                title = @"a";
                break;
            case 1:
                title = @"b";
                break;
            case 2:
                title = @"c";
                break;
        }

但是,如果你的选择器视图中有100个数字,这将是非常不切实际的。我相信你可以看到我在下面尝试做什么。它给了我错误

expression is not an integer constant expression

如何在选择器视图中获取0到100之间的数字?如果有更好的方法来获取用户选择1到100之间的数字,请随意发表评论。

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString * title = nil;

    if (pickerView.tag == 1) // this is otherPickerview
    {
        otherpickerview
        for (int i = 2; i < 100; i++){
            switch(row) {
                case i:
                    title = [NSString stringWithFormat:@"%d", i];
                    break;

            }


        }

    }

2 个答案:

答案 0 :(得分:1)

让我们试试:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return _arr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
// you can switch to other UIPickerView, and return title for row which you want.
// don't need to loop whenever titleForRow is called.
return _arr[row];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.navigationController setNavigationBarHidden:YES];

_arr = [[NSMutableArray alloc]init];
for (int i = 0; i<100; i++) {
    NSString *str = [NSString stringWithFormat:@"%d",i];
    [_arr addObject:str];
}
_pickerView.dataSource = self;
_pickerView.delegate = self;
}

答案 1 :(得分:0)

这可以使用数组以更简单的方式完成。您所要做的就是创建包含所有可能标题的数组,然后根据titleForRow:方法中的当前行访问它们。这是一个例子:

- (NSArray *)items
{
    static NSArray *items = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        items = @[@"a",@"b",@"c"]; // ..... etc ...
    });

    return items;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    if (pickerView.tag == 1) {
        NSArray *items = [self items];

        if (row < items.count) {
            return [self items][row];
        }

        return nil;

    } else {
        return @"something else";
    }
}

此外,如果您的数据是严格的字母数字字符,则可以从NSCharacterSet中的字符创建数组,请参阅:

NSArray from NSCharacterset