如何在iOS 7下更改UIPickerView中文本的颜色? [英] How do I change the color of the text in a UIPickerView under iOS 7?
问题描述
我知道 pickerView:viewForRow:forComponent:reusingView
方法,但是当使用视图
时传入 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:
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;
}
如果你想改变选择栏的颜色,我发现我必须将2个单独的 UIViews
添加到包含 UIPickerView
的视图中,间隔35磅,选择器高度为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()
因为在使用 attributionTitleForRow()
时从未调用过。
Remember when you use the method: You don't need to implement titleForRowInComponent()
as it is never called when using attributedTitleForRow()
.
这篇关于如何在iOS 7下更改UIPickerView中文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!