How to set top-left alignment for UILabel for iOS application?
It's fairly easy to do. Create a UILabel
sublcass with a verticalAlignment
property and override textRectForBounds:limitedToNumberOfLines
to return the correct bounds for a top, middle or bottom vertical alignment. Here's the code:
SOLabel.h
#import <UIKit/UIKit.h>typedef enum{ VerticalAlignmentTop = 0, // default VerticalAlignmentMiddle, VerticalAlignmentBottom,} VerticalAlignment;@interface SOLabel : UILabel @property (nonatomic, readwrite) VerticalAlignment verticalAlignment;@end
SOLabel.m
@implementation SOLabel-(id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (!self) return nil; // set inital value via IVAR so the setter isn't called _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];}@end
Rather than re-explaining, I will link to this rather extensive & highly rated question/answer:
Vertically align text to top within a UILabel
The short answer is no, Apple didn't make this easy, but it is possible by changing the frame size.
I found a solution using AutoLayout in StoryBoard.
1) Set no of lines to 0 and text alignment to Left.
2) Set height constraint.
3) The height Constraint should be in Relation - Less Than or Equal
4)
override func viewWillLayoutSubviews() { sampleLabel.sizeToFit() }
I got the result as follows :