我已经看到了使用选择器视图的示例,其中将选择器的值硬编码到这样的源代码中

- (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;

            }


        }

    }

===============>>#1 票数: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;
}

===============>>#2 票数: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中的字符创建数组,请参见以下内容:

来自NSCharacterset的NSArray

  ask by Leahcim translate from so

未解决问题?本站智能推荐: