0

I have the following code to add the attributed string to the UITextView text. I need to add the custom font and font size to it in swift. How to do it?

    func setAttributedString(string: String) -> NSAttributedString {
    let attrString = NSMutableAttributedString(string: string)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 7
    paragraphStyle.minimumLineHeight = 7
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSRange(location: 0, length:attrString.length))
    attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 30), range: NSRange(location: 0, length:attrString.length))
    return attrString
  }

I need to add the custom font and font size to the following function. How to achieve this?

Chelsea Shawra
  • 1,593
  • 4
  • 22
  • 43
  • Possible duplicate of [How do I make an attributed string using Swift?](https://stackoverflow.com/questions/24666515/how-do-i-make-an-attributed-string-using-swift) – Tushar Sharma Oct 05 '17 at 18:35
  • You will hopefully get your answer from link. Just convert syntax to latest swift syntax. – Tushar Sharma Oct 05 '17 at 18:36
  • https://stackoverflow.com/questions/46460034/swift-3-render-textview-using-nsattributedstring-but-want-change-the-default-fon/46460119#46460119 – Vini App Oct 05 '17 at 18:41

2 Answers2

1

In Swift 3

let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!, 
              NSAttributedStringKey.foregroundColor: UIColor.white]

let attributedString  = NSMutableAttributedString(string: "Your string" , attributes: attributes)
Community
  • 1
  • 1
Nims
  • 431
  • 6
  • 15
1

Use the initializer init(string:attributes:)

https://developer.apple.com/documentation/foundation/nsattributedstring/1408136-init

let attrString = NSMutableAttributedString(string: string, attributes:
            [NSFontAttributeName:UIFont(
            name: "Georgia",
            size: 18.0)!])
    //Add more attributes here
AmandaR
  • 81
  • 3