I use NSAttributedString
to generate a string with two different sizes. By default, its bottom alignment looks like this:
But I want to center it vertically, like this:
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.
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With