UILabel negative line spacing
Building off of Eric Murphey's answer, I've created an extension in Swift 4 syntax.
extension UILabel{
public func zeroLineSpace(){
let s = NSMutableAttributedString(string: self.text!)
let style = NSMutableParagraphStyle()
let lineHeight = self.font.pointSize - self.font.ascender + self.font.capHeight
let offset = self.font.capHeight - self.font.ascender
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
}
}
Simply call it like so
myUiLabel.zeroLineSpace()
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
CGFloat minMaxLineHeight = (font.pointSize - font.ascender + font.capHeight);
NSNumber *offset = @(font.capHeight - font.ascender);
NSRange range = NSMakeRange(0, labelText.length);
[style setMinimumLineHeight:minMaxLineHeight];
[style setMaximumLineHeight:minMaxLineHeight];
if (isCentered) {
[style setAlignment:NSTextAlignmentCenter];
}
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:range];
[attrString addAttribute:NSBaselineOffsetAttributeName
value:offset
range:range];
This should get you near zero spacing on the text and should be safe to use with any font type and size.
Please see the following documentation from Apple setLineSpacing - NSMutableParagraphStyle , value must not be negative
setLineSpacing:
Sets the distance in points added between lines within the paragraph toaFloat
.- (void)setLineSpacing:(CGFloat)aFloat
Discussion
This value must be nonnegative.
There are also methods related to the minimum and maximum height for lines… probably setting line space to 0 and modifying the height could help you to achieve the effect you want-