Como mudo a cor do texto em um UIPickerView no iOS 7?


117

Estou ciente do pickerView:viewForRow:forComponent:reusingViewmétodo, mas ao usar viewele passa, reusingView:como faço para alterá-lo para usar uma cor de texto diferente? Se eu usar, view.backgroundColor = [UIColor whiteColor];nenhuma das visualizações aparecerá mais.



2
@AaronBrager. Que Não é uma duplicata o link fornecido por vc é perguntado depois disso.
— Gajendra K Chauhan

Respostas:


323

Existe uma função no método delegado que é mais elegante:

Objective-C:

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = @"sample title";
    NSAttributedString *attString = 
        [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    return attString;
}

Se você quiser alterar as cores da barra de seleção também, descobri que tinha que adicionar 2 separados UIViewspara a exibição que contém oUIPickerView espaçamento de 35 pontos para uma altura do seletor de 180.

Swift 3:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName:UIColor.white])
}

Swift 4:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
}

Swift 4.2:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}

Lembre-se de quando usar o método: Você não precisa implementar titleForRowInComponent()porque ele nunca é chamado durante o uso attributedTitleForRow().


De longe, essa é a melhor resposta, pois também funciona para visualizações do selecionador com mais de um componente.
— PKCLsoft

29

Postagem original aqui: posso mudar a cor da fonte do datePicker no iOS7?

- (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.backgroundColor = [UIColor grayColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
    label.text = [NSString stringWithFormat:@" %d", row+1];
    return label;
}

// number Of Components
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// number Of Rows In Component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:   (NSInteger)component
{
    return 6;
}

Essa solução funciona bem para uma exibição de seleção contendo um único componente. Se você tiver mais de 1, os rótulos se sobreporão pelo que posso ver.
— PKCLsoft

23
  1. Vá para o storyboard
  2. Selecione PickerView
  3. Vá para o inspetor de identidade (3ª guia)
  4. Adicionar Atributo de Tempo de Execução Definido pelo Usuário
  5. KeyPath = textColor
  6. Type = Color
  7. Valor = [cor de sua escolha]

captura de tela


Explique sua resposta
— Gwenc37

11
é um trabalho pela metade, o texto é preto, mas quando você rola no seletor, ele muda para branco
— Shial

4
Funciona apenas se você rolar
— Chris Van Buskirk

Olá @ chris-van-buskirk Verifique meu add-on [_thePrettyPicker selectRow: prettyIndex inComponent: 0 animated: YES];
— WINSergey de

7

no Xamarin, substitua o método UIPickerModelView GetAttributedTitle

public override NSAttributedString GetAttributedTitle(UIPickerView picker, nint row, nint component)
{
    // change text white
    string title = GetTitle (picker, row, component); // get current text from UIPickerViewModel::GetTitle
    NSAttributedString ns = new NSAttributedString (title, null, UIColor.White); // null = font, use current font
    return ns;
}


2

Eu tive o mesmo problema com um pickerView usando dois componentes. Minha solução é semelhante à anterior, com algumas modificações. Como estou usando dois componentes, é necessário extrair de dois arrays diferentes.

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor blueColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];

    //WithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 60)];

    if(component == 0)
    {
        label.text = [countryArray objectAtIndex:row];
    }
    else
    {
        label.text = [cityArray objectAtIndex:row];
    }
    return label;
}

2

Swift 4 (atualização para a resposta aceita)

extension MyViewController: UIPickerViewDelegate{
    }

    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        return NSAttributedString(string: "your-title-goes-here", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
    }
}

1
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
        UILabel* pickerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 37)];
        pickerLabel.text = @"text";
        pickerLabel.textColor = [UIColor redColor];
        return pickerLabel;
}
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.