【问题标题】:Setting font using NSAttributedString使用 NSAttributedString 设置字体
【发布时间】:2016-12-17 10:49:59
【问题描述】:

尝试使用 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
    }
}

颜色改变,字体 - 不是:

我做错了什么?

【问题讨论】:

    标签: swift uipickerview nsattributedstring


    【解决方案1】:

    简短的回答是您没有做错任何事情,这是 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
        }
    }
    

    【讨论】:

    • 感谢您的详细解答。是的,它使用自定义视图。出于性能原因,始终尽量不要使用视图
    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多