本文介绍了如何在 iOS 7 下更改 UIPickerView 中文本的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 pickerView:viewForRow:forComponent:reusingView 方法,但是当使用 view 时,它传入 reusingView: 如何更改它以使用不同的文本颜色?如果我使用 view.backgroundColor = [UIColor whiteColor]; 没有视图显示了.

I'm aware of the pickerView:viewForRow:forComponent:reusingView method, but when using the view it passes in reusingView: how do I change it to use a different text color? If I use view.backgroundColor = [UIColor whiteColor]; none of the views show up anymore.

推荐答案

委托方法中有一个函数更优雅:

There is a function in the delegate method that is more elegant:

目标 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;
}

如果您还想更改选择栏颜色,我发现我必须向包含 UIPickerView 的视图添加 2 个单独的 UIViews,相距 35 pts选择器高度为 180.

If you want to change the selection bar colors as well, I found that I had to add 2 separate UIViews to the view containing the UIPickerView, spaced 35 pts apart for a picker height of 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])
}

记住当你使用这个方法时:你不需要实现 titleForRowInComponent() 因为它在使用 attributedTitleForRow() 时永远不会被调用.

Remember when you use the method: You don't need to implement titleForRowInComponent() as it is never called when using attributedTitleForRow().

这篇关于如何在 iOS 7 下更改 UIPickerView 中文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:35