【问题标题】:Changing the fontsize and font color of the NSAttributedString更改 NSAttributedString 的字体大小和字体颜色
【发布时间】:2020-10-12 19:21:56
【问题描述】:

如何在swift中更改NSAttributedString的字体大小和字体颜色?

 @IBOutlet weak var detailsTextView: UITextView!

 if let data = htmltext.data(using: String.Encoding.utf8, allowLossyConversion: true)
 {
        do
        {
            let newFont =  UIFont(name: "Georgia", size: 22.0) ?? UIFont()    
            let attributedText = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)            
            detailsTextView.attributedText = attributedText
        }
        catch{}
}

htmltext是需要设置为UILabel的html值

【问题讨论】:

  • yourlabel.attributetext = 属性文本在哪里
  • @Anbu.Karthik 我这里没有提到。
  • @PrabuRaj 你可以试试下面的代码 swift 3.0
  • @Anbu.Karthik 你对此有什么答案吗?因为没有一个答案能给我预期的结果..
  • @PrabuRaj 你能添加你的 html 字符串的样子吗?

标签: ios swift nsattributedstring


【解决方案1】:

斯威夫特 5.2

String 扩展中添加以下属性:

extension String
{
    var htmlToAttributedString: NSAttributedString?
    {
        guard let data = data(using: .utf8) else { return nil }
        do
        {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .right

            let content = try NSMutableAttributedString(data: data, options: [.documentType:     NSAttributedString.DocumentType.html, .characterEncoding:     String.Encoding.utf8.rawValue], documentAttributes: nil)

            content.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle,
                                   NSAttributedString.Key.font: UIFont.alJazeera(.regular(20)),
                                   NSAttributedString.Key.foregroundColor: UIColor.appDark],
                                  range: NSMakeRange(0, content.length))

            return content
        }
        catch
        {
            return nil
        }
    }
}

那就轻松使用吧:

textView.attributedText = myText.htmlToAttributedString

注意:UIFont.alJazeera(.regular(20))UIFont扩展中定义的静态方法,UIColor.appDark也是UIColor扩展中定义的静态属性

【讨论】:

    【解决方案2】:

    你就是这样做的:

    var attributedString = try? NSAttributedString(data: inst.desc.data(using: String.Encoding.unicode), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    var newString = NSMutableAttributedString(attributedString: attributedString!)
    var range: NSRange = [0, newString.length]
    newString.enumerateAttribute(NSFontAttributeName, in: range, options: .longestEffectiveRangeNotRequired, using: {(_ value: Any, _ range: NSRange, _ stop: Bool) -> Void in
        var replacementFont = UIFont(name: "Palatino-Roman", size: 14.0)
        newString.addAttribute(NSFontAttributeName, value: replacementFont!, range: range)
    })
    label.attributedText = newString
    

    【讨论】:

      【解决方案3】:

      这是设置 NSAttributedString 属性的方式:

      let attributes: [String : Any] = [NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightThin),
          NSForegroundColorAttributeName: UIColor.blue]
      
      let attributedText = NSAttributedString(string: "Some string", attributes: attributes)
      

      【讨论】:

      • ofSize 参数采用 CGFloat。
      • 这不会呈现字符串中的 html 标签。它显示了没有渲染的html文本..
      • 我已经在 Playground 中尝试过,效果很好。你的htmltextdeclared 怎么样?
      • 只有很少的
        标签
      【解决方案4】:

      使用这个

      let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText)
      
      // Enumerate through all the font ranges
      newAttributedString.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, 
      newAttributedString.length), options: []) { value, range, stop in
      guard let currentFont = value as? UIFont else {
          return
      }
      
      // An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc.
      // Here we describe the replacement font as coming from the "Hoefler Text" family
      let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptorFamilyAttribute: "Hoefler Text"])
      
      // Ask the OS for an actual font that most closely matches the description above
      if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptorFamilyAttribute]).first {
          let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize)
          newAttributedString.addAttributes([NSFontAttributeName: newFont], range: range)
      }
      label.attributedText = newAttributedString
       }
      

      【讨论】:

        【解决方案5】:

        斯威夫特 3.0

        你可以试试这个方法,

        let finaltext = "<span style='font-family:Georgia; font-size: 20px'>\(Your html string)</span>"
        detailsTextView.attributedText = finaltext.html2AttributedString
        

        并添加扩展名

        extension String {
            var html2AttributedString: NSAttributedString? {
                do {
                    return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
                } catch {
                    print(error)
                    return nil
                }
            }
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-19
          • 1970-01-01
          相关资源
          最近更新 更多