如何为uipickerviews提供多个数据数组?

时间:2015-10-28 14:19:46

标签: ios swift uipickerview

我想要完成的任务:我有5个不同的UITextfields。我希望用户能够使用UIPickerviews填写这些字段。此外,我希望每个选择器视图具有不同的范围和/或类型的值,以便为每个文本字段进行选择。

我尝试使用switch语句为每个文本字段使用不同数组的多个pickerviews执行此操作。但是,我不认为这是实现这一目标的最有效方式。有人可以阐明为pickerviews实现不同数据数组的最佳实践吗?

2 个答案:

答案 0 :(得分:2)

您可以通过以下代码

仅使用一个PickerView来实现您的目标
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (pickerSelected) {

        case LANGUAGE:
            return [languageArray count];
            break;
        case GENDER:
            return [genderArray count];
            break;
        case COUNTRY:
            return [countryArray count];
            break;
        case CITY:
            return [cityArray count];
            break;

        default:
            return 0;
            break;
    }

    return 0;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (pickerSelected) {

        case LANGUAGE:
            return [languageArray objectAtIndex:row];
            break;
        case GENDER:
            return [genderArray objectAtIndex:row];
            break;

        case COUNTRY:
            return [[countryArray objectAtIndex:row] countryName];
            break;

        case CITY:
            return [cityArray objectAtIndex:row];

        default:
            return @"";
            break;
    }

    return nil;
}
  • languageArraygenderArraycountryArray代表你的。{ 不同的阵列

  • pickerSelected可以是enumint值,您可以根据不同的UITextField设置该值。 每个UITextField都具有PickerView

  • 的唯一值

答案 1 :(得分:2)

根据需要将一个数组变为可变或不可变,并在.m文件中使用textField声明。

使用TextField Delegate方法:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
    {
      currentText=textField;
    if (textField==yourTextfield)
    {
        arrCurrent=YourCurrentArray;
        [yourTextfield setInputView:pickerObj];
        [pickerObj setBackgroundColor:[UIColor whiteColor]];
        [yourTextfield setInputAccessoryView:toolObj];
        [self pickerView:pickerObj didSelectRow:[pickerObj selectedRowInComponent:0] inComponent:0];

    }
    else if (textField==yourTextfield2)
    {
        arrCurrent=YourCurrentArray2;
        [yourTextfield2 setInputView:pickerObj];
        [pickerObj setBackgroundColor:[UIColor whiteColor]];
        [yourTextfield2 setInputAccessoryView:toolObj];
        [self pickerView:pickerObj didSelectRow:[pickerObj selectedRowInComponent:0] inComponent:0];

    }
    }

在pickerView Delegate中:

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component
{

        [currentText setText:[arrCurrent objectAtIndex:row]];

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component
{
    return [arrCurrent objectAtIndex:row];

}

希望对你有所帮助.. :)