Search code examples
iosobjective-cuipickerview

How to populate UIpickerView with array after changing its text colour?


I want to populate my picker view after customising its text. When I could populate it with array I'm not able to change it text colour. I've searched everywhere and I find both separate either it they have changed the text colour or populated it with array. The below is my code what I've tried.

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

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

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
    label.textAlignment = NSTextAlignmentCenter;
    if (row == 0) 
    {
        label.text = self.CityList[0];
    }
    else if (row == 1) 
    {
        label.text = self.CityList[1];
    }
    else if (row == 2) 
    {
        label.text = self.CityList[2];
    }
    else if (row == 3) 
    {
        label.text = self.CityList[3];
    }
    else if (row == 4) 
    {
        label.text = self.CityList[4];
    }
    else if (row == 5) 
    {
        label.text = self.CityList[5];
    }
    return label;
}

this code actually works fine but when I have too many in my array it is definitely not efficient to implement it this way. please suggest me an efficient method.


Solution

  • Change your method like this:

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
    {
    
        UILabel *label = (UILabel *)view;
        //Check if the current view requested is a reused one, If not then create a new one
        if (!label)
        {
            label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
        }
    
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
        label.textAlignment = NSTextAlignmentCenter;
    
        //Assign the text of the label to the NSString at the index of "row" from your data array
        label.text = self.CityList[row];
    
        return label;
    }