2

I want to increase the Line Spacing in UILabel but I can't figure it out how.

I found this solution [https://stackoverflow.com/a/39158698/8633963] on Stackoverflow but my Xcode always displays this:

Use of unresolved identifier 'NSParagraphStyleAttributeName'

I think the answer is right but it did not work for me. Can anyone help with this problem?

Enes
  • 79
  • 1
  • 9
  • The answer is there in mentioned SO link. Did you look at others' answer? https://stackoverflow.com/a/39158698/8633963 Opinion. Instead of defining programmatically, better to do the same from Interface builder. – Mani Apr 21 '18 at 09:42

4 Answers4

9

Swift 5

import UIKit

extension UILabel {
    
    func setLineHeight(lineHeight: CGFloat) {
        guard let text = self.text else { return }
        
        let attributeString = NSMutableAttributedString(string: text)
        let style = NSMutableParagraphStyle()
        
        style.lineSpacing = lineHeight
        attributeString.addAttribute(
            NSAttributedString.Key.paragraphStyle,
            value: style,
            range: NSMakeRange(0, attributeString.length))
        
        self.attributedText = attributeString
    }

}
Dzhek
  • 101
  • 1
  • 2
3

In Swift 4 in this case you have to use NSAttributedStringKey.paragraphStyle instead of NSParagraphStyleAttributeName

schmidt9
  • 4,436
  • 1
  • 26
  • 32
1

This worked for me.

import UIKit

    extension UILabel {

        func setLineHeight(lineHeight: CGFloat) {
            let text = self.text
            if let text = text {
                let attributeString = NSMutableAttributedString(string: text)
                let style = NSMutableParagraphStyle()

                style.lineSpacing = lineHeight
                attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, count(text)))
                self.attributedText = attributeString
            }
        }
    }
Fahad Azeem
  • 541
  • 7
  • 14
-2

Check out this ridiculously simple solution that works!

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CommentTVCCell

    // Configure the cell...


    cell.myLabel?.text = "\n[\(indexPath.row + 1)]\n\n" + itemArray[indexPath.row].name

    //

    return cell 
}

//Notice the use of the \n to load a return or as many as you wish. Make sure they are within a string designation.

Glenn Tisman
  • 163
  • 1
  • 6