委托方法中有一个更为优雅的函数:
目标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;
}
如果您还想更改选择栏的颜色,我发现我必须向UIViews
包含的视图添加2个单独的视图UIPickerView
,相隔35磅,选择器高度为180。
斯威夫特3:
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let string = "myString"
return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName:UIColor.white])
}
斯威夫特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()
。