using colors in uipickerview

Discussion in 'iOS Programming' started by theprizerevealed, Mar 5, 2017.

  1. theprizerevealed macrumors member

    Joined:
    Feb 26, 2016
    #1
    I want to create a uipickerview that will highlight the text in the uipickerviews' current selection with a certain color. I don't mean the background color of the picker rather that actual text the picker is showing in the selected row. I have found a couple websites that discuss how to do it with attributed strings but I wonder if it's possible to do it without attributed string?

    Here are the websites that I found:

    http://joshhighland.com/2009/09/17/uipickerview-spinning-multiple-components/

    https://stackoverflow.com/questions...cted-row-label-color-in-picker-view-swift-1-2
     
  2. AxoNeuron macrumors 65816

    AxoNeuron

    Joined:
    Apr 22, 2012
    Location:
    The Left Coast
    #2
    Why would you avoid using NSAttributedString? I don't see why you would?

    In any case, there's two ways to go about doing what you want to do:

    Code:
        func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
       {
            let view = UIView();
            let label = UILabel();
            label.textColor = UIColor.green;
            view.addSubview(label);
            //adjust frame rect's here to make sure it's actually visible
            return view
        }
    
    ^ This is really ugly in my opinion but it would work. You could also create a custom UIView xib interface file and that would be just fine.

    If you're willing to break down and use NSAttributedString it is FAR easier and simpler. Here's an example:
    Code:
        func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?
        {
            return NSAttributedString(string: "a pretty color", attributes: [NSFontAttributeName : UIFont(name: "Helvetica", size: 14)!, NSForegroundColorAttributeName : UIColor.red]);
        }
    
     

Share This Page