Search code examples
swiftuitextviewnsattributedstring

How to add strings with different fonts in UItextField?


I'm trying to add two part of text with different font parameters. But they always get value from first string. And there one strange thing, font color is set independently.

let descriptionTextView: UITextView = {
    let view = UITextView()


    let attributedText = NSMutableAttributedString(string: "Text", attributes:
        [.font:UIFont.boldSystemFont(ofSize: 20),
    .foregroundColor: UIColor.blue])

    attributedText.append(NSAttributedString(string: "\n\n\n Other text", attributes:
        [.font: UIFont.italicSystemFont(ofSize: 5),
         .foregroundColor: UIColor.gray]))

    view.attributedText = attributedText


    view.translatesAutoresizingMaskIntoConstraints = false
    view.textAlignment = .center
    view.font = UIFont.boldSystemFont(ofSize: 20)
    view.isEditable = false
    view.isScrollEnabled = false

    return view
}()

This is how it look in simulator


Solution

  • Remove

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