Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
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
 
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]);
    }
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.