简体   繁体   中英

UIPickerView set selected row background color (now also for iOS 14)

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM