使用NSAttributedString设置字体

时间:2016-12-17 10:50:00

标签: swift uipickerview nsattributedstring

使用NSAttributedString在我的pickerView中尝试更改字体:

public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    guard let castDict = self.castDict else {
        return nil
    }
    let name = [String](castDict.keys)[row]
    switch component {
    case 0:
        return NSAttributedString(string: name, attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)])
    case 1:
        guard let character = castDict[name] else {
            return NSAttributedString(string: "Not found character for \(name)", attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)])
        }
        return NSAttributedString(string: character, attributes: [NSForegroundColorAttributeName : AppColors.LightBlue.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)])
    default:
        return nil
    }
}

颜色已更改,字体 - 不是:

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:1)

简短的回答是你没有做错任何问题,这是Apple的一个问题,因为他们没有在UIPickerView中无法更改字体的任何地方写。

但是,有一种解决方法。

UIPickerViewDelegate您必须实施func pickerView(_ pickerView:, viewForRow row:, forComponent component:, reusing view:) -> UIView。通过这个实现,您将能够为每一行提供自定义UIView。

以下是一个例子:

func pickerView(_ reusingpickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    if let pickerLabel = view as? UILabel {
        // The UILabel already exists and is setup, just set the text
        pickerLabel.text = "Some text"

        return pickerLabel
    } else {
        // The UILabel doesn't exist, we have to create it and do the setup for font and textAlignment
        let pickerLabel = UILabel()

        pickerLabel.font = UIFont.boldSystemFont(ofSize: 18)
        pickerLabel.textAlignment = NSTextAlignment.center // By default the text is left aligned

        pickerLabel.text = "Some text"

        return pickerLabel
    }
}