如何在UIPickerView中一起滚动多个组件?

时间:2013-05-23 08:14:31

标签: iphone ios scroll uipickerview

我遇到了与滚动UIPickerView的多个组件相关的问题。 我用两个组件创建了uipickerview,但是当我滚动其中一个组件时,其他组件也会滚动但是在第二个组件之后。

代码:

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

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
       return [finalArray count];
}


-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0) {
    return [[finalArray objectAtIndex:row] objectForKey:@"value1"];
}else if (component == 1){
    return [[finalArray objectAtIndex:row] objectForKey:@"value2"];
}else{
    return nil;
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
        [thePickerView selectRow:row inComponent:0 animated:NO];
        [thePickerView selectRow:row inComponent:1 animated:NO];
}

我想要的是滚动任何组件应该滚动所有组件,就像只有一个组件一样。 它不应该显示自动滚动的第二部分。

如果有可能,你建议做什么?...

2 个答案:

答案 0 :(得分:0)

您可以使用参数中的视图为同一组件定义2个或更多不同的标签:在此示例中,我创建了2个标签(labelName和lableValue),并指定了不同的位置和大小(固定)以及不同的字体。 / p>

//Update view for each row
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* labelName;
    UILabel* labelValue;

    UIView* container;
    UIFont *font1 = [UIFont fontWithName:@"Arial" size:19.0f];
    UIFont *font2 = [UIFont fontWithName:@"Arial" size:15.0f];

    if(view==nil)
    {
        //Define the container for the 2 lables (or more)
        container = [[UIView alloc] init];

        //Create the new labels defining position and size
        labelName = [[UILabel alloc] initWithFrame:CGRectMake(2, 2 , 250, 20)];
        labelValue = [[UILabel alloc] initWithFrame:CGRectMake(260, 2 , 90, 20)];

        //Add the labels to the container
        [container addSubview:labelName];
        [container addSubview:labelValue];

        //Customize the font for the lables
        labelName.font = font1;
        labelValue.font = font2;

        //To show the label frame (just to test the position and size, change the backcolor)
        labelName.backgroundColor = [UIColor yellowColor];
        labelValue.backgroundColor = [UIColor greenColor];
    }

在此代码之后,您可以检查行和列以将字符串分配给标签。使用此代码,您可以在相同的空间中放置两个或更多字符串,而无需考虑字体大小(如果连接2个字符串并且不使用固定字体,则会出现问题)

答案 1 :(得分:-1)

Oke我得到了Anupdas的评论......

通过给出空格数量,我可以解决问题。

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    __weak NSString *lbl1 = [NSString stringWithString:[[finalArray objectAtIndex:row] objectForKey:@"value1"]];
    lbl1 = [lbl1 stringByAppendingString:@"                                            "];
    lbl1 = [lbl1 stringByAppendingString:[[finalArray objectAtIndex:row] objectForKey:@"value2"]];
    return lbl1;
}