Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center two fonts with different different sizes vertically in an NSAttributedString

I use NSAttributedString to generate a string with two different sizes. By default, its bottom alignment looks like this:

baseline aligned sizes

But I want to center it vertically, like this: vertically centered sizes

To be clear, this is a single attributed string, not two or more. This is a simplified example to describe my question, what I'd actually like to do is more complex.

like image 455
user2608857 Avatar asked Oct 21 '13 06:10

user2608857


People also ask

Can we apply vertical alignment for text?

Use the line-height Property to Align Text Vertically in CSS If we have single-line text, we can use the line-height property to align the text vertically within a div . The line-height CSS property sets the height of a line box. It is used to set the distance between lines of text.


2 Answers

I'd say the easiest thing to do is just manipulate the NSBaselineOffsetAttributeName attribute for the text in question:

NSBaselineOffsetAttributeName

The value of this attribute is an NSNumber object containing a floating point value indicating the character’s offset from the baseline, in points. The default value is 0.

To center, you'd take the difference between height of the large text and the height of the smaller text and halve it, then use that as the baseline adjustment.

like image 125
Ben Lachman Avatar answered Oct 09 '22 01:10

Ben Lachman


Here is a working example to vertically align smaller text using NSBaselineOffsetAttributeName.

NSString *bigString   = @"BIG"; NSString *smallString = @"Small String"; NSString *fullString = [NSString stringWithFormat:@"%@ %@", bigString, smallString];  NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString];  NSRange bigStringRange = NSMakeRange(0, bigString.length); NSRange smallStringRange = NSMakeRange(bigStringRange.length, smallString.length);  [string beginEditing];   //Set big string font and size [string addAttribute:NSFontAttributeName                value:[UIFont systemFontOfSize:28.0]                range:bigStringRange];  //set small string font and size [string addAttribute:NSFontAttributeName                value:[UIFont systemFontOfSize:18.0]                range:smallStringRange];  //Set small string baseline offset [string addAttribute:NSBaselineOffsetAttributeName                value:[NSNumber numberWithFloat:3.0]  //adjust this number till text appears to be centered                range:smallStringRange];  [string endEditing]; 
like image 40
Yas Tabasam Avatar answered Oct 08 '22 23:10

Yas Tabasam