1

in a UItextView I am using paragraphStyle to space the new paragraphs between them.

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 20

However, I would need to insert a new line without it being a new paragraph. Here is an example

Test first line.
Test new line.

Test new paragraph

I tried to use \r or to assign paragraphSpacing = 0 to the new line but it always distances it. How could I go about inserting a new line without inserting a new paragraph? It's possible to do it?

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Stefano Vet
  • 567
  • 1
  • 7
  • 18

1 Answers1

1

You should set paragraphStyle.spacing = 0 for first line then paragraphStyle.spacing = 20 and paragraphStyle.spacing = 0 for the third line. So basically spacing changes the space after the line it was set for not before.

    let line1 = NSMutableAttributedString(string: "Test first line\n")
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.spacing = 0
    attrStr.setAttributes([.paragraphStyle: paragraphStyle,
                           .font: UIFont.systemFont(ofSize: 15, weight: .regular),
                           .foregroundColor: UIColor.black],
                          range: NSMakeRange(0, line1))
    
    let line2 = NSMutableAttributedString(string: "Test new line.\n")
    let paragraphStyle2 = NSMutableParagraphStyle()
    paragraphStyle2.lineSpacing = 20
    line2.setAttributes([.paragraphStyle: paragraphStyle2,
                         .font: UIFont.systemFont(ofSize: 15, weight: .regular),
                         .foregroundColor: UIColor.black],
                          range: NSMakeRange(0, line2.string.count))
    
    let line3 = NSMutableAttributedString(string: "Test new paragraph")
    let paragraphStyle3 = NSMutableParagraphStyle()
    paragraphStyle3.spacing = 0
    line3.setAttributes([.paragraphStyle: paragraphStyle3,
                         .font: UIFont.systemFont(ofSize: 15, weight: .regular),
                         .foregroundColor: UIColor.black],
                          range: NSMakeRange(0, line3.string.count))
    
    line1.append(line2)
    line1.append(line3)
    
    textView.attributedText = line1
Bulat Yakupov
  • 440
  • 4
  • 13
  • 1
    for different cursor height https://stackoverflow.com/questions/20207961/uitextview-linespacing-causes-different-cursor-height-inbetween-paragraph-lines – Stefano Vet Oct 15 '22 at 12:27