使用 NSAttributedString 设置字体

Setting font using 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
    }
}

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

我做错了什么?

简短的回答是您没有做错任何事情,这是 Apple 方面的问题,因为他们没有在任何地方写明在 UIPickerView 中不能更改字体。

但是,有一个解决方法。

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

这是一个例子:

func pickerView(_ pickerView: 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
    }
}