簡體   English   中英

UIPickerView 設置選定行的背景顏色(現在也適用於 iOS 14)

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

我在這里找到了這個代碼:

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

但是,正如評論中所述,它有一個問題:

它為標簽着色,而不是選擇器本身。 因此,當您滾動到一端或另一端時,會出現一個空白點,您可以在其中看到白色背景。

我只需要更改所選行的背景顏色。

我發現在 iOS 14 中,我現在在選擇器的選定項目上獲得了灰色背景顏色。 目前的要求是擺脫它。 所以這似乎有效。

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

(“safe”是一個執行數組邊界檢查並在索引無效時返回 nil 的運算符)

我從這里得到了這個想法: https : //stackoverflow.com/a/53740571/826946

我們也可以通過繼承 UIPickerView 並將Andy的答案放在 layoutSubviews 重寫方法中來實現。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM