Search code examples
iosswiftxcodeswift3

Control Line Spacing in UITextView


enter image description here

I'm trying to remove line spaces in an UITextView but can't seem to figure it out. I tried textContainer.lineFragmentPadding and NSLineBreakMode, but with no luck.


Solution

  • You should use NSAttributedString instead of String like this:

    let attributedString = NSMutableAttributedString(string: "Your text")
    
    // *** Create instance of `NSMutableParagraphStyle`
    let paragraphStyle = NSMutableParagraphStyle()
    
    // *** set LineSpacing property in points ***
    paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
    
    // *** Apply attribute to string ***
    attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
    if let font = UIFont(name: "AvenirNextCondensed-Regular", size: font_size) {
        attributedString.addAttribute(NSAttributedString.Key.font, value: font, range: NSMakeRange(0, attributedString.length))
    }
    
    // *** Set Attributed String to your label ***
    textView.attributedText = attributedString