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?

3

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.