How to bold TextView with custom Font in Swift?

869 Views Asked by At

I want to change my text in textview to BOLD and Italic on button click; but when I do this the custom font which is I am using for my textview also changed; but I want to use custom font.

Following is the code for bold textview

textView.font = UIFont.boldSystemFont(ofSize: 20)

I want to use custom font even when using bold or italic style

I have tried this but it does not work.

func attributedText() -> NSAttributedString {
    let attributedString = NSMutableAttributedString(string: textView.text, attributes: [NSAttributedString.Key.font:(name: CustomFont, size: CGFloat(fontSize))]

    let boldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15.0)]

    // 4
    return attributedString
}

And called as:

textView.attributedText = attributedText()
1

There are 1 best solutions below

0
timbre timbre On

You can't make a regular font look bold, instead you need to have a bold font face for your custom font family (separate file) and add it together with regular font to your project's .plist as shown here.

For example if your font is called a CustomFont, then you'd add the following files into your project

CustomFont
CustomFont-Bold

Now you get a bold font as

let boldFont = UIFont(name: "CustomFont-Bold", size: ...)