Search code examples
iosswiftuipickerviewnsattributedstring

iOS picker view with normal and bold text labels in Swift


I need to have a picker view with some entries, that have normal font weight and some with bold font weight. Finding out how to create an attributed string is not the problem, so I put everything together but I couldn't see a difference. The first row is not bold and not bigger. Different colors do work, though.

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let darkColor = UIColor.blackColor()
    let lightColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3)                             
    if row == 0 {
        return NSAttributedString(string: "first row bold and black", attributes: [NSForegroundColorAttributeName:darkColor, NSFontAttributeName : UIFont.boldSystemFontOfSize(20)])
    } else {
        return NSAttributedString(string: "other rows gray and normal", attributes: [NSForegroundColorAttributeName:lightColor])
    }
}

Solution

  • Use the viewForRow, rather than attributedTitleForRow, and you get a lot more control

    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
    {
        let pickerLabel = UILabel()
    
        if row == 0
        {
            pickerLabel.text = "first row bold and black"
            pickerLabel.textColor = UIColor.blackColor()
            pickerLabel.font = UIFont.boldSystemFontOfSize(20)
        }
        else
        {
            pickerLabel.text = "other rows gray and normal"
            pickerLabel.textColor = UIColor.grayColor()
        }
    
        pickerLabel.textAlignment = NSTextAlignment.Center
        return pickerLabel
    }
    

    enter image description here