Ok, maybe I\'m missing something really simple and I apologize if that\'s the case, however, I\'ve googled every permutation of the title and have not found! So this is sim
Call the UIPickerView
instance's -viewForRow:forComponent:
method to get the UIView *
object. Then set that view's background UIColor
.
Swift version of @alessandro-pirovano answer
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let rowSize = pickerView.rowSize(forComponent: component)
let width = rowSize.width
let height = rowSize.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)
let label = UILabel(frame: frame)
label.textAlignment = .center
label.text = rows[row]
return label
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard let label = pickerView.view(forRow: row, forComponent: component) as? UILabel else {
return
}
label.backgroundColor = .orange
}
UIPickerView has delegate to set NSAttributeString for title at row and component we can set attribute color like below:
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *attrs = @{NSForegroundColorAttributeName : [UIColor redColor]};
NSString *title = @"title"
return [[NSAttributedString alloc] initWithString:title attributes:attrs];
}
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()
}
}