How to Vertically Align Text Using UILabel and NSAttributedString

uilabel vertical alignment
uilabel vertical alignment programmatically
text align vertical ios
uitextview vertical alignment
vertical alignment label ios
uilabel attributedtext alignment
uilabel center text
uitextview center text horizontally

I am using UILabel and NSAttributedString to set linespacing for label texts in IOS7. But when i use this the text doesnt seems aligned centrally on the Label. Here is my code to set text (attributed) to the label.

-(void)setText:(NSString *)text
{
    [super setText:text];

    if(text)
        [self setLineSpace];
}
-(void)setLineSpace
{
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        NSMutableAttributedString *string=[[NSMutableAttributedString alloc]initWithString:self.text];

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.alignment=NSTextAlignmentJustified;
        [paragraphStyle setLineSpacing:4] ;
//        paragraphStyle.minimumLineHeight =0;
//        paragraphStyle.maximumLineHeight=7;
     //  CTTextAlignment alignment = kCTCenterTextAlignment;
        [string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
        self.text=nil;
        self.attributedText=string;

        [self setBackgroundColor:[UIColor redColor]];

    }

}

Here are some Screenshots ,BTW am subclassing UILabel to and overriding the setter to implement linespacing.

Actually I solved it ....:) :) .The problem was with the custom font i was using.

Took some R&D but now it seems working

Just created a subclass for label and override some default methods.

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{

    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];

    if(([self.font.fontName isEqualToString:@"Gotham"]||[self.font.fontName isEqualToString:@"Gotham-Bold"]||[self.font.fontName isEqualToString:@"Gotham-Medium"])&&((int)[[[UIDevice currentDevice] systemVersion] floatValue])==6&&self.verticalAlignment==AlignMiddle)
    {
        textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
        return [self addToRect:textRect x:0 y:2];
    }
    return [self addToRect:textRect x:0 y:0.5];
}

-(void)drawTextInRect:(CGRect)requestedRect
{
    if(((int)[[[UIDevice currentDevice] systemVersion] floatValue])>=7)
       [super drawTextInRect:[self addToRect:requestedRect x:0 y:0.5]];
    else
    {
        CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
        [super drawTextInRect:actualRect];
    }
}
-(CGRect)addToRect:(CGRect)rect x:(CGFloat)dx y:(CGFloat) dy
{
    rect=CGRectMake(rect.origin.x+dx, rect.origin.y+dy, rect.size.width, rect.size.height);
    return rect;
}
-(CGRect)makeRect:(CGRect)rect x:(CGFloat)dx y:(CGFloat) dy
{
    rect=CGRectMake(dx,dy, rect.size.width+dx, rect.size.height+dy);
    return rect;
}
-(CGRect)makeRects:(CGRect)rect x:(CGFloat)dx y:(CGFloat) dy
{
    rect=CGRectMake(rect.origin.x,rect.origin.y, rect.size.width+dx, rect.size.height+dy);
    return rect;
}
-(void)truncateToFit
{
    if([[[UIDevice currentDevice] systemVersion] floatValue] < 7)
    {
        [self sizeToFit];
        CGRect frame=self.frame;
    if(frame.size.height<self.frame.size.height)
        self.frame=[self makeRects:frame x:0 y:0.5];
    }
    else
    {
        self.frame=[self makeRects:self.frame x:0 y:0.5];
        [self sizeToFit];
    }
}

-(void)truncatesToFit
{
    self.lineBreakMode=NSLineBreakByTruncatingTail;

        self.numberOfLines=2;
        [self sizeToFit];
        self.frame=[self makeRects:self.frame x:0 y:0.5];
}




-(void)truncatesToFit:(NSInteger )linesCount

{

    self.numberOfLines=linesCount;

    [self sizeToFit];

    self.frame=[self makeRects:self.frame x:0 y:0.5];

}

Center Text Vertically in TextView?, If you want to center the text vertically, you should probably be using UILabel. You can still use the same NSAttributedString to center the text horizontally. Horizontally aligning a UILabel in iOS is easy enough, but unfortunately vertically isn’t as simple. There are many ways to achieve vertically aligned text, each with their pros and cons. I’m going to go through a few methods, and then show my preferred method for vertically aligned text. Using a UITextField

Probably you can't do it with UILabel in the simple way.

If possible, you can use UITextField to vertically align content.

Else using NSAttributedString and the text of label, you can adjust Line-Height (Not sure).

Changing baselineOffset moves text…, I am trying to vertically center the text in a UILabel with a minimum line height. Create and set the attributed text let attributedText = NSAttributedString(string:  The problem comes up in a recent project of mine. I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.

Can be done via the attributed string:

ObjC:

// shift the text down 10 pixels
[string addAttribute:NSBaselineOffsetAttributeName value:@(-10) range:NSMakeRange(0, string.length)];

Swift:

// shift the text up 10 pixels
string.addAttributes([NSAttributedStringKey.baselineOffset:10], range: range)

iOS, NSTextAlignmentJustified , NSTextAlignmentNatural. Vertical alignment in UILabel is not supported out of the box: Vertically align text to top within a UILabel. Vertically align text to top within a UILabel in swift H_Developer Apr 30, 2019 5465 0 There's no way to set the vertical align on a UILabel , but you can get the same effect by changing the label's frame.

You may use some other workaround - a custom UILabel

NWLabel.m

#import "NWLabel.h"

@implementation NWLabel

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return nil;

_verticalAlignment = VerticalAlignmentTop;

return self;
}


-(VerticalAlignment) verticalAlignment
{
return _verticalAlignment;
}

-(void) setVerticalAlignment:(VerticalAlignment)value
{
_verticalAlignment = value;
[self setNeedsDisplay];
}

// align text block according to vertical alignment settings
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
CGRect result;
switch (_verticalAlignment)
{
    case VerticalAlignmentTop:
        result = CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height);
        break;
    case VerticalAlignmentMiddle:
        result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height) / 2, rect.size.width, rect.size.height);
        break;
    case VerticalAlignmentBottom:
        result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height), rect.size.width, rect.size.height);
        break;
    default:
        result = bounds;
        break;
}
return result;
}

-(void)drawTextInRect:(CGRect)rect
{
CGRect r = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:r];
}

NWLabel.h

#import <UIKit/UIKit.h>

typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;

@interface NWLabel : UILabel
{
   @private  VerticalAlignment _verticalAlignment;
}

@property (nonatomic, readwrite, assign) VerticalAlignment verticalAlignment;


@end

UILabel / Text alignment / Essential iOS, Vertical alignment in UILabel is not supported out of the box: http://stackoverflow.​com/questions/1054558/vertically-align-text-to-top-within-a-uilabel. Found a  I know this is an old post but vertically aligning text is a HUGE problem (at least for me it is) and I figured that I should share this solution since I couldn't find one myself. Using drawRect is a little expensive in my opinion. The proper way to get a UILabel to vertically align is to not use a UILabel.

When there's only one line of text displayed in your custom label, don't set the line spacing.

Vertically align text to top iOS UILabel, Solution: You cannot be able to align the label vertically.At the same time you can be able to set the number of line in UILabel.If you set that  Ok the problem: I have a UILabel which gets text dynamically assigned to it. If I resize the label to cover the entire view controller the text is stuck in the middle. I found a bunch of solutions which say to add the following code: detailsLabel.numberOfLines = 0; detailsLabel.sizeToFit() However this doesn't do anything.

Justify Text in UILabel iOS, Create NSDictionary for text attributes and create attributed string. UILabel / Text alignment / Essential iOS, Vertical alignment in UILabel is not supported out​  Assigning a new value to this property also replaces the value of the text property with the same string data, although without any formatting information. In addition, assigning a new value updates the values in the font , text Color , and other style-related properties so that they reflect the style information starting at location 0 in the

Vertical align not correct after setting textAligment · Issue #24 , I added a line on the addLineBreak(attrString:) method. a case where I need the text to be horizontal and vertical aligned. let mutAttrString = NSMutableAttributedString(attributedString: attrString) var But a workaround could be to use the horizontal alignment fix, and then make the UILabel height fit to  1) Use an NSAttributedString and more the baseline with NSBaselineOffsetAttributeName. TTTAttributedLabel is a good shortcut. 2) Use CoreText and CoreGraphics to render your own text layout in a CGLayer within a custom UIView subclass and effectively create your own UILabel equivalent. This is HARD!

Vertical alignment - Swift, Hi everybody, to show in my app Japanese Text with phonetic text I've I would like that it shows the text on the center of the label, like original UILabel. I'm trying to create a label that show nsattributedstring that use ruby  vertically vertical nsbaselineoffsetattributename not centered ios nsattributedstring How to calculate the height of an NSAttributedString with given width in iOS 6 Top-aligning text of different sizes within a UILabel

Comments
  • @preetam i want to verically align the strings ..see the screenshot news is more aligned to 'up-part' of the label/..
  • Well you need UILabel only, i mean if you can use UITextField then inside xib it provides control section there you can directly change the alignment of the text without writing of code
  • @hussainShabbir textview is not an option for me i need uilabel
  • Why do you need to worry about linespacing if your label is only displaying a single line of text? Or is the rest of the text not visible?
  • your question related stackoverflow.com/questions/1054558/…
  • This is also not working also i had to manually write code for Horizontal alignment
  • Original answer is here posted by @ivan.m .. And worked for me discussions.apple.com/thread/1759957?tstart=0
  • unfortunately i need line spacing
  • ye ios 7 doesnt have a nyc line spacing (default) so i need to provide that manually.. :(