ios - 如何在 iOS 7 下更改 UIPickerView 中文本的颜色?

我知道 pickerView:viewForRow:forComponent:reusingView 方法,但是在使用 view 时它会传入 reusingView: 如何是否将其更改为使用不同的文本颜色?如果我使用 view.backgroundColor = [UIColor whiteColor]; 所有 View 都不再显示。

最佳答案

委托(delegate)方法中有一个更优雅的函数:

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

如果你也想更改选择栏颜色,我发现我必须在包含 UIPickerView 的 View 中添加 2 个单独的 UIViews,间隔 35 pts选择器高度为 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() 时永远不会调用它。

https://stackoverflow.com/questions/19232817/

相关文章:

objective-c - 有没有办法抑制 Xcode 中的警告?

objective-c - 在 switch 语句中声明变量

ios - 如何使用 Swift 播放本地视频?

objective-c - 如何使用 Objective-C 解析 JSON?

objective-c - NSObject +load 和 +initialize - 他们做什么

ios - UIRefreshControl - 当 UITableViewController 在

ios - 如何从 NSDate 获取小时和分钟?

ios - UIButton自定义字体垂直对齐

iphone - 导航栏出现在带有新 iOS7 SDK 的 View 上

ios - 在 iOS 的 UITextView 中检测属性文本的点击