Question

I am trying to align a UILabel or a NSAttributedString within a UILabel so that a specified character is always aligned to the center of the screen.

One way to do it is to use two labels. One for the specified character and the substring from the left and make it right-aligned. The second for the substring right of the specified character.

I was wondering is there a way to simplify the process (now with the almighty NSAttributedString). Or maybe with a NSDateFormatter.

Sample usage: Set the ":" in the time format (e.g. "12:40", "9:14", "3:04 PM") to always be centred to the screen (or to anything else). Regardless of different fonts/times/AM-PM symbols etc.

Thanks for your help.

Was it helpful?

Solution

You can probably use sizeWithAttributes: to get the size for the first half of the text and then adjust the UILabel position.

NSString* firstHalf = [[label.text componentsSeparatedByString:@":"] objectAtIndex:0];
CGSize firstHalfSize = [firstHalf sizeWithAttributes:textAttributes];

CGRect labelFrame = label.frame;
labelFrame.origin.x = center.x-firstHalfSize.width;
label.frame = labelFrame;

That would set the beggining of ":" on the center. If you want to put the middle of that character on the center you can add the following:

NSString* firstHalf = [[label.text componentsSeparatedByString:@":"] objectAtIndex:0];
CGSize firstHalfSize = [firstHalf sizeWithAttributes:textAttributes];

CGSize charSize = [@":" sizeWithAttributes:textAttributes];

CGRect labelFrame = label.frame;
labelFrame.origin.x = self.view.bounds.size.width/2-firstHalfSize.width-charSize.width/2;
label.frame = labelFrame;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top