How to set font size on NSAttributedString

Martin Muldoon picture Martin Muldoon · Aug 30, 2017 · Viewed 46.7k times · Source

Edit - This has been marked as duplicate, but as I state below, I am looking for a Swift solution. Everything I've found is written in Objective C.

I am trying to convert HTML into an NSAttributedString, but can't figure how to set the font style and size. All of the examples are in Objective C which I'm not skilled in. How can I set the font style/size to System 15 (as an example)

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
    }

EDIT...... I've tried several ways. I can't get it to work. I'm now getting an error message: Type of expression is ambiguous without more context. It's pointing to the NSAttributedString I've tried the following:

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)

Answer

Vikas Rajput picture Vikas Rajput · Aug 30, 2017
  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

font

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

Shadow

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

Underline

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

Textcolor

 let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

BackGroud Color

  let myAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]