user3000847
user3000847

Reputation: 191

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?

Upvotes: 0

Views: 1644

Answers (2)

Maulik Salvi
Maulik Salvi

Reputation: 279

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component ==0)
    {
        NSString *title = @"maulik";
        NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
        return attString;
    }
    if(component ==1)
    {
        NSString *title = @"fenil";
        NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];

        return attString;
    }
    return 0;
}

Upvotes: 4

Hani Ibrahim
Hani Ibrahim

Reputation: 1449

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 
    }
}

Upvotes: -1

Related Questions