4

I found this code here:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = (UILabel*) view;
    if (label == nil)
    {
        label = [[UILabel alloc] init];
    }

    [label setText:@"Whatever"];

    // This part just colorizes everything, since you asked about that.

    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor blackColor]];
    CGSize rowSize = [pickerView rowSizeForComponent:component];
    CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
    [label setFrame:labelRect];

    return label;
}

But, as stated in the comments, it has a problem:

It colorizes the labels, but not the picker, itself. So, when you roll to one end or the other, there's a blank spot where you can see the white background.

All I need is to change the background colour of the selected row.

Andy Weinstein
  • 2,639
  • 3
  • 21
  • 32
Zaxter
  • 2,939
  • 3
  • 31
  • 48

2 Answers2

4

I found that in iOS 14 I am now getting a gray background color on the selected item of the picker. Requirement currently is to get rid of that. So this seems to work.

pickerView.subviews[safe:1]?.backgroundColor = UIColor.clear 

("safe" is an operator that does array bounds checking and returns nil if the index is invalid)

I got the idea from here: https://stackoverflow.com/a/53740571/826946

Andy Weinstein
  • 2,639
  • 3
  • 21
  • 32
  • I found something almost identical to the code I use here, you can give them an upvote. https://stackoverflow.com/a/30593673/826946 Not sure where the post that I got my code from is. – Andy Weinstein Jan 16 '21 at 16:44
1

We also can achieve that by subclassing UIPickerView and putting Andy's answer inside layoutSubviews overrided method.

class PickerView: UIPickerView {
   override func layoutSubviews() {
      super.layoutSubviews()
      subviews[safe:1]?.backgroundColor = UIColor.clear 
   }
}
Sajjad
  • 51
  • 7