我知道 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/