How to change color of selected row in UIPickerView

前端 未结 10 789
孤独总比滥情好
孤独总比滥情好 2020-12-03 10:25

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

相关标签:
10条回答
  • 2020-12-03 11:24

    Call the UIPickerView instance's -viewForRow:forComponent: method to get the UIView * object. Then set that view's background UIColor.

    0 讨论(0)
  • 2020-12-03 11:27

    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
    }
    
    0 讨论(0)
  • 2020-12-03 11:27

    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];
    

    }

    0 讨论(0)
  • 2020-12-03 11:28

    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()
        }
    }
    
    0 讨论(0)
提交回复
热议问题