IOS无论如何要在整个app中拥有NSAttributedString。迅速

时间:2016-04-20 22:54:59

标签: ios swift nsattributedstring uifont

我有一个超级瘦的字体。在Photoshop中,我在字体上添加了笔触,使其看起来更具吸引力。将它传输到iOS时我无法添加笔划,除非我使用了NSAttributedString。通过使用NSAttributedString,我得到了一个我的UILabel,看看它在photoshop中的外观,但问题是,当我的应用程序完成时,我将有数百个UILabel。有没有办法我不必手动将每个UILabel连接到其各自的控制器并逐个设置其attributionText。任何建议都会有所帮助。

3 个答案:

答案 0 :(得分:0)

基于@ AdamPro13建议,您可以为NSAttributedString创建协议扩展名:

所以,用这样的东西创建NSAttributedStringExtension.swift

protocol NSAttributedStringExtension {
    static func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString
}

extension NSAttributedString : NSAttributedStringExtension {
    class func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString {

        let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:color]
        return NSAttributedString(string: string, attributes: attrs)
    }
}

您可以为不同的标签类型制作几种不同的功能。 然后在您的标签上申请(粗略代码):

let label:UILabel
let font:UIFont
let color:UIColor
label.attributedText = NSAttributedString.attributed("test", font: font, color: color)

注意:您可以在协议扩展功能中设置的字体和颜色

答案 1 :(得分:0)

如果您正在使用故事板并希望正常使用UILabel,那么您可以尝试创建UILabel子类,如下所示,并在故事板中将其用作自定义类。这将有效地用您想要的attributedText替换文本,尽管在运行时之前不会看到它。

class CustomLabel: UILabel {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        let attrs = [NSFontAttributeName: UIFont.boldSystemFontOfSize(19),
                     NSForegroundColorAttributeName: UIColor.blueColor()]
        attributedText = NSAttributedString(string: text!, attributes: attrs)
    }
}

答案 2 :(得分:0)

我只是在搜索,然后偶然发现了这个问题。我认为您想要一个UILabel的类别。我以前使用过的旧的Cocoapod库中有一种非常有用的方法,叫做 GPKit https://github.com/glennposadas/gpkit-ios。但是下面的代码已更新并记录了。

import UIKit

/// Category for UILabel helper functions
extension UILabel {
    /// A helper function for setting up the normal properties of the label.
    /// This means that the label has no special attributes.
    /// This uses the system font.
    func setup(_ text: String, fontSize: CGFloat, weight: UIFont.Weight = .regular, italic: Bool = false, textColor: UIColor = .lalaDarkGray, numberOfLines: Int = 1, textAlignment: NSTextAlignment = .natural) {
        self.font = italic ? UIFont.italicSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize, weight: weight)
        self.text = text
        self.textColor = textColor
        self.numberOfLines = numberOfLines
        self.textAlignment = textAlignment
    }

    /**
     Sets up the label with two different kinds of attributes in its attributed text.

     - Author: Glenn

     - Important:
         - primaryString = "Total:"
         - secondaryString = "123"
         - This means that the function will concat the secondary string into the primary string and highlights the secondary string.
         - Using the highlightedText means the highlightedText itself is in the primaryString.

     - parameters:
        - primaryString: the normal attributed string.
        - secondaryString: the bold or highlighted string.
        - highlightedText: this one is like the secondary string, if this is provided, then the secondaryString is ignored. This is to be used if the highlighted text is not to be concatinated at the end of the primaryString
     */
    func setAttributedText(
        primaryString: String,
        textColor: UIColor,
        font: UIFont,
        secondaryString: String = "",
        secondaryTextColor: UIColor? = nil,
        secondaryFont: UIFont? = nil,
        highlightedText: String? = nil,
        textAlignment: NSTextAlignment = .center,
        numberOfLines: Int = 1,
        lineHeightMultiple: CGFloat = 1) {

        var textToBeHighlighted = ""
        var completeString: String!

        self.numberOfLines = numberOfLines

        if let highlightedText = highlightedText {
            textToBeHighlighted = highlightedText
            completeString = primaryString
        } else {
            if secondaryString.hasValidValue() {
                textToBeHighlighted = secondaryString
                completeString = "\(primaryString) \(secondaryString)"
            } else {
                completeString = primaryString
            }
        }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = textAlignment
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let completeAttributedString = NSMutableAttributedString(
            string: completeString, attributes: [
                .font: font,
                .foregroundColor: textColor,
                .paragraphStyle: paragraphStyle
            ]
        )

        let secondStringAttribute: [NSAttributedString.Key: Any] = [
            .font: secondaryFont ?? font,
            .foregroundColor: secondaryTextColor ?? textColor,
            .paragraphStyle: paragraphStyle
        ]

        let range = (completeString as NSString).range(of: textToBeHighlighted)

        completeAttributedString.addAttributes(secondStringAttribute, range: range)

        self.attributedText = completeAttributedString
    }
}

您可以像这样在每个标签中使用它:

internal lazy var label_Total: UILabel = {
    let label = UILabel()
    label.setAttributedText(
        primaryString: "Total".localized(),
        textColor: .gray,
        font: UIFont.systemFont(ofSize: 14.0),
        secondaryString: "",
        secondaryTextColor: .blue,
        secondaryFont: UIFont.systemFont(ofSize: 14.0, weight: customFontWeight)
    )
    return label
}()