Search code examples
swiftuilabelremoving-whitespace

line spacing is more because of font


I am using Changa font in one of my app. The issue in the font what I am using have extra white space at top & bottom.

I am simply setting text & font to the UILabel as below.

myLabel.font = UIFont(name: "Changa-Regular", size: 14)!
myLabel.text = "Lorem ipsum"

If you see below screenshot (second yellow label) you will notice that space between 2 fonts is very big.

Also for test I give background color to first label (first yellow). If you see font is having white space at top and bottom too.

Any idea how can we remove or decrease that white spacing that is there default in the font?

enter image description here


Solution

  • I found an extension which helped to fix the issue.

    public func zeroLineSpace(){
        let s = NSMutableAttributedString(string: self.text!)
        let style = NSMutableParagraphStyle()
        let lineHeight = self.font.pointSize - self.font.ascender + self.font.capHeight + 10
        let offset = self.font.capHeight - self.font.ascender + 5
        let range = NSMakeRange(0, self.text!.count)
        style.maximumLineHeight = lineHeight
        style.minimumLineHeight = lineHeight
        style.alignment = self.textAlignment
        s.addAttribute(.paragraphStyle, value: style, range: range)
        s.addAttribute(.baselineOffset, value: offset, range: range)
        self.attributedText = s
        self.lineBreakMode = .byTruncatingTail
    }