Search code examples
iosswiftuipickerview

Change the label of UIPickerView


I am trying to change the font of UIPickerView.

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
    let label = UILabel()

    label.font = UIFont(name:"SynchroLetPlain", size:20)
    //label.font = UIFont.systemFont(ofSize: 17) //Even I use systemFont, it doesn't show nothing
    return label
}

It is ok for compile though, no text is shown.

Where is defferent? I have checked SynchroLetPlain is included in project.


Solution

  • Try this one

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
            var label: UILabel
            if let view = view as? UILabel {
                label = view
            } else {
                label = UILabel()
            }
            label.font = UIFont(name:"SynchroLetPlain", size:20)
            // where data is an Array of String
            label.text = "" // set data here
            return label
    
        }
    

    Additionally:

    func printFonts()
        {
            for fontFamilyName in UIFont.familyNames {
                print("-- \(fontFamilyName) --", terminator: "")
                for fontName in UIFont.fontNames(forFamilyName: fontFamilyName ) {
                    print(fontName)
                }
                print(" ", terminator: "")
            }
        }
    

    Call this function, which gives you the exact name of the font which you have to use to set the font.