如何在 NSAttributedString 上设置字体大小

How to set font size on NSAttributedString

编辑 - 这已被标记为重复,但正如我在下面所述,我正在寻找 Swift 解决方案。我发现的所有内容都写在 Objective C.

我正在尝试将 HTML 转换为 NSAttributedString,但不知道如何设置字体样式和大小。所有的例子都在Objective C里面,我不熟练。如何将字体style/size设置为System 15(作为例子)

private func stringFromHtml(string: String) -> NSAttributedString? {
        do {
            let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
            if let d = data {
                let str = try NSAttributedString(data: d,
                                                 options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],                                                  documentAttributes: nil)
                return str
            }
        } catch {
        }
        return nil
    }

编辑......我已经尝试了几种方法。我无法让它工作。我现在收到一条错误消息:没有更多上下文,表达式类型不明确。它指向 NSAttributedString 我试过以下方法:

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
  if let d = data {
     let str = try NSAttributedString(data: d,
                       attributes: myAttribute,
                       options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
请检查这个
var attrString = NSAttributedString(string: "labelText", attributes: [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "system", size: 12)])
label.attributedText = attrString
let myString = "Swift Attributed String"
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) 

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

字体

let myAttribute = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)! ]

阴影

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSShadowAttributeName: myShadow ]

下划线

let myAttribute = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue ]

文字颜色

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

背景颜色

let myAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]

可以这样设置

let attribute: [String : Any] = [NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightThin),
    NSForegroundColorAttributeName: UIColor.red]

let attributedText = NSAttributedString(string: "Your String", attributes: attribute)

首先你需要将数据转换成字符串然后使用这段代码

let  attributes = [
   NSForegroundColorAttributeName: UIColor.black,
            ]
try NSAttributedString(string: "", attributes: attributes)

在Swift中你可以使用:

let stringWithAttribute = NSAttributedString(string: selectedFilter ?? "",
                                             attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)])

唯一对我有用的是将 HTML 包裹在 <span> 中并在那里应用样式:

let modifiedFontString = "<span style=\"font-family: Lato-Regular; font-size: 14; color: rgb(60, 60, 60)\">" + originalHTMLString + "</span>"

试试这个扩展:

extension String {

    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }

    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }

    func convertToAttributedString() -> NSAttributedString? {
        let modifiedFontString = "<span style=\"font-family: Lato-Regular; font-size: 14; color: rgb(60, 60, 60)\">" + self + "</span>"
        return modifiedFontString.htmlToAttributedString
    }
}

然后你这样使用它:

someLabel.attributedString = someHTMLString.convertToAttributedString()

希望对您有所帮助!

检查 swift 5:

extension String {
    func getAttributedString<T>(_ key: NSAttributedString.Key, value: T) -> NSAttributedString {
       let applyAttribute = [ key: T.self ]
       let attrString = NSAttributedString(string: self, attributes: applyAttribute)
       return attrString
    }
}

您可以在此处查看更多属性样式: https://developer.apple.com/documentation/foundation/nsattributedstring/key

使用

// Background Color
let attributedString = "YOUR_STRING".getAttributedString(.backgroundColor, value: UIColor.blue)

// Forground Color
let attributedString = "YOUR_STRING".getAttributedString(.foregroundColor, value: UIColor.red)

// Font
let attributedString = "YOUR_STRING".getAttributedString(.font, value: UIFont.boldSystemFont(ofSize: 15))

// Underline
let attributedString = "YOUR_STRING".getAttributedString(.underlineStyle, value: NSUnderlineStyle.single)

// Underline Color
let attributedString = "YOUR_STRING".getAttributedString(.underlineColor, value: UIColor.black)

    
// set attributed text on a UILabel
yourLabel.attributedText = attributedString