How to set font size on NSAttributedString
In Swift you can use:
let stringWithAttribute = NSAttributedString(string: selectedFilter ?? "",
attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)])
The only thing that worked for me is to wrap the HTML in a <span>
and apply the style there:
let modifiedFontString = "<span style=\"font-family: Lato-Regular; font-size: 14; color: rgb(60, 60, 60)\">" + originalHTMLString + "</span>"
Try this extension:
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
}
}
And you use it like this:
someLabel.attributedString = someHTMLString.convertToAttributedString()
Hope it helps!
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 ]
Background Color
let myAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]