How to change color of selected row in UIPickerView
The correct format for viewForPicker is:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = (UILabel*) view;
if (label == nil)
{
label = [[UILabel alloc] init];
}
[label setText:@"Whatever"];
// This part just colorizes everything, since you asked about that.
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor blackColor]];
CGSize rowSize = [pickerView rowSizeForComponent:component];
CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
[label setFrame:labelRect];
return label;
}
The problem with the code above is: it colorizes the labels, but not the picker, itself. So, when you roll to one end or the other, there's a blank spot where you can see the white background. Setting [myPicker setBackgroundColor...] doesn't do what one might hope.
Swift implementation
extension PickerViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
var color: UIColor!
if pickerView.selectedRowInComponent(component) == row {
color = UIColor.redColor()
} else {
color = UIColor.blackColor()
}
let attributes: [String: AnyObject] = [
NSForegroundColorAttributeName: color,
NSFontAttributeName: UIFont.systemFontOfSize(15)
]
return NSAttributedString(string: rows[row], attributes: attributes)
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//this will trigger attributedTitleForRow-method to be called
pickerView.reloadAllComponents()
}
}
Normally, I use this method:
I use the custom view for show the row item
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = (id)view;
if (!label)
{
label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = _arrayStringPicker[row];
}
return label;
I change color of row selected with:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
UILabel *labelSelected = (UILabel*)[pickerView viewForRow:row forComponent:component];
[labelSelected setTextColor:[UIColor redColor]];
}