implemented title attributed for row in picker view did not change the font?

妖精的绣舞 提交于 2019-12-13 16:19:06

问题


I tried to change the font of the title in my picker view, but for some reason I could not. I can change the color of the title, but the font remains intact?

 func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let attrTitle = NSAttributedString(string: splitPickerSource[row], attributes: [NSFontAttributeName: UIFont(name: "Avenir-Heavy", size: 17.0)!, NSForegroundColorAttributeName: UIColor.darkGray])
        return attrTitle
    }

Alternatively I can implement viewForRow delegate method for the UIPickerView and add a new label from there.

Some debugging message as maddy suggested when try to printout attrTitle

Share Bill With{ NSColor = "UIExtendedSRGBColorSpace 0.117647 0.117647 0.117647 1"; NSFont = "<UICTFont: 0x7fb5f8d14080> font-family: \"Avenir-Heavy\"; font-weight: bold; font-style: normal; font-size: 14.00pt";

Anyone has any idea about this situation and why can't I modify the font in attributedTitleForRow delegate method?


回答1:


Try this out

//MARK: Setting picker select label size

    /**
     Called by Picker to To add customized text to fit size
     - parameter pickerView: The picker view requesting the data.
     - parameter row: Index of row
     - parameter component: component Index
     */

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {        
        let pickerLabel = UILabel() //get picker label that come

        pickerLabel.lineBreakMode = .byWordWrapping //Wrapping if needed

        pickerLabel.numberOfLines = 0; //So it comes to single line 

        pickerLabel.textColor = UIColor.white //setting colour 

        self.currentValue = NamesStringArray[row] //Array with Titles

        let data = NamesStringArray[row] //Taking Index Title

        let title = NSAttributedString(string: data, attributes: [NSAttributedStringKey.font : UIFont(name: "Avenir-Heavy", size: 40.0)!]) //here add attributes

        pickerLabel.attributedText = title //setting attributed text as title

        pickerLabel.sizeToFit() //Size to fit //If needed

        pickerLabel.adjustsFontSizeToFitWidth = true //if needed

        return pickerLabel //return value

    }




回答2:


You have made a typo that's why it is not working. It should be

    let attrTitle = NSAttributedString(string: splitPickerSource[row], attributes: [NSFontAttributeName: UIFont(name: "Avenir-Heavy", size: 17.0)!, NSForegroundColorAttributeName: UIColor.darkGray]) 

I removed the extra size: 14 after NSFontAttributeName was supposed to end.



来源:https://stackoverflow.com/questions/40876229/implemented-title-attributed-for-row-in-picker-view-did-not-change-the-font

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!