Search code examples
iosuipickerview

Difficulties changing text color of two component UIPickerView


I want to be able to change the text color for both rows, I'm using this code:

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    NSString *rowItem = [weight objectAtIndex: row];


    UILabel *lblRow = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView bounds].size.width, 44.0f)];

    [lblRow setTextAlignment:UITextAlignmentCenter];

    [lblRow setTextColor: [UIColor redColor]];

    [lblRow setText:rowItem];

    [lblRow setBackgroundColor:[UIColor clearColor]];

    return lblRow;
}

It makes the two components in the UIPickerView the same data but it changes the color. How do I make it two change the color for both components without changing the data?


Solution

  • you have two params row and component

    you will have to if condition the component and get the data you want

    -(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
        if (component == 0)
            NSString *rowItem = [weight objectAtIndex: row];
            UILabel *lblRow = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView bounds].size.width, 44.0f)];
            [lblRow setTextAlignment:UITextAlignmentCenter];
            [lblRow setTextColor: [UIColor redColor]];
            [lblRow setText:rowItem];
            [lblRow setBackgroundColor:[UIColor clearColor]];
            return lblRow;
        } else {
            // Adjust the second component 
        }
    }