9

Do you have any ideas about line spacing with UITextView? I cannot apply it. Below it is my code.

import UIKit

class DetailViewController: UIViewController {
    @IBOutlet weak var itemTextView: UITextView!
    var txtString: String?
    var txtTitleBar:String?

    override func viewDidLoad() {
        super.viewDidLoad()
        //navigationController?.navigationItem.title = "Love"
        self.title = txtTitleBar

        //self.tabBarController?.navigationItem.title = "My Title"
        itemTextView.text = txtString
        itemTextView.font = UIFont(name: "Arial-Regular", size:20)
        itemTextView.font = .systemFont(ofSize: 25)
        (itemTextView.font?.lineHeight)! * 5
    }
}

enter image description here

Eric Aya
  • 69,000
  • 34
  • 174
  • 243
Ravy Chheng
  • 133
  • 1
  • 1
  • 6

4 Answers4

24

You need to use an attributed string and assign a paragraph style. For example:

let style = NSMutableParagraphStyle()
style.lineSpacing = 20
let attributes = [NSParagraphStyleAttributeName : style]
textView.attributedText = NSAttributedString(string: txtString, attributes: attributes)

See this SO answer for more details on attributed string usage: How do I make an attributed string using Swift?

Community
  • 1
  • 1
garrettmurray
  • 3,258
  • 1
  • 23
  • 23
5

Xcode 9.2 Swift 4

let style = NSMutableParagraphStyle()
style.lineSpacing = 0
let attributes = [NSAttributedStringKey.paragraphStyle : style]
txtViewAbout.attributedText = NSAttributedString(string: txtViewAbout.text, attributes: attributes)
Khawar Islam
  • 2,062
  • 1
  • 24
  • 44
4

Xcode 10.1 Swift 4.2

let style = NSMutableParagraphStyle()
style.lineSpacing = 19
let attributes = [NSAttributedString.Key.paragraphStyle: style]
textView.attributedText = NSAttributedString(string: model.text, attributes: attributes)
LionHere
  • 9
  • 1
  • 2
0

Using typingAttributes will make sure that, the attributes apply to new text that the user enters.

    let style = NSMutableParagraphStyle()
    style.lineSpacing = 10
    let attributes = [NSAttributedString.Key.paragraphStyle : style )
    ]
    textView.typingAttributes = attributes
Ahmad
  • 195
  • 1
  • 12