Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel negative line spacing

I've got a UILabel and I want to make the line spacing less than 0 (so the text moves closer together rather than further away). What am I doing wrong?

    UIFont* customFont = [UIFont fontWithName:@"BebasNeue" size:70];
    NSString * text = @"Their \nIdeas";

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
    paragrahStyle.lineSpacing = -30;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [text length])];

    UILabel *lbl1 = [[UILabel alloc] init];
    lbl1.frame = CGRectMake(120, 0, viewWidth, 300);
    lbl1.backgroundColor = [UIColor clearColor];
    lbl1.textColor = grayColor;
    lbl1.numberOfLines = 2;
    lbl1.attributedText = attributedString;
    lbl1.userInteractionEnabled = NO;
    lbl1.font = customFont;
    [view addSubview:lbl1];
    [lbl1 setTransform:CGAffineTransformMakeRotation(0.35)];
like image 944
Max Hudson Avatar asked Apr 09 '14 15:04

Max Hudson


1 Answers

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()
like image 59
Chris Stillwell Avatar answered Oct 31 '22 13:10

Chris Stillwell