Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Really close lines with NSAttributedString?

Tags:

I want to have two lines of text appear really close together (small line spacing) for a button. I have the following code:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"50 WPM"];  NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init]; paragrapStyle.alignment = NSTextAlignmentCenter; paragrapStyle.lineSpacing = -10;  [string addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, string.length)];  UIFont *font1 = [UIFont systemFontOfSize:22.0]; [string addAttribute:NSFontAttributeName value:font1 range:NSMakeRange(0, string.length - 4)];  UIFont *font = [UIFont systemFontOfSize:15.0]; [string addAttribute:NSFontAttributeName value:font range:NSMakeRange(string.length - 3, 3)];  [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, string.length)];  [self.button setAttributedTitle:string forState:UIControlStateNormal]; 

But as linespacing can't be negative, it doesn't get nearly as close as I'd like it to be. It looks like this:

enter image description here

Is there any way to get them closer?

like image 805
Doug Smith Avatar asked Oct 24 '13 00:10

Doug Smith


2 Answers

Well if you have an attribute string then everything should be possible. :) You just have to look more.

- (void)setMinimumLineHeight:(CGFloat)aFloat - (void)setMaximumLineHeight:(CGFloat)aFloat 

Try

[paragraphStyle setLineSpacing:0.0f]; [paragraphStyle setMaximumLineHeight:7.0f]; 

You will realise that maximumLineHeight is not maximumLineSpacing. ^^

This for example is with setMaximumLineHeight:12];

enter image description here

like image 67
nscoding Avatar answered Oct 18 '22 08:10

nscoding


Here a little extension in Swift3 which supports negative lineSpacing

extension UILabel {     func set(lineSpacing: CGFloat, textAlignment: NSTextAlignment = NSTextAlignment.center) {         if let text = self.text {             let paragraphStyle = NSMutableParagraphStyle()             if lineSpacing < 0 {                 paragraphStyle.lineSpacing = 0                 paragraphStyle.maximumLineHeight = self.font.pointSize + lineSpacing             } else {                 paragraphStyle.lineSpacing = lineSpacing             }             let attrString = NSMutableAttributedString(string: text)             attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))             self.attributedText = attrString             self.textAlignment = textAlignment         }     } } 
like image 44
rushelmet Avatar answered Oct 18 '22 10:10

rushelmet