Problem
I have a UILabel
height that can display up to two lines, and if there is only one row, it is vertically centered. How can you make it top-aligned?
Answer 1: Use
sizeToFit
Change
UILabel
The height
Nevan king,1969 Likes
Vertical alignment that cannot be changed directly UILabel
, but the same effect can be achieved by changing the label frame height to small. In order to see clearly, I labeled the label Orange.
The simplest approach is to:
[myLabel sizeToFit];
SizeToFit
If the content is longer than one line, numberOfLines
set to 0 (that is, no limit on the number of rows).
0; [myLabel sizeToFit];
One problem is that if your text is centered horizontally, the sizeToFit
frame width is reduced after execution, and the text shrinks to the upper-left corner. The solution is to save the label's width first, and sizeToFit
then set it back after execution.
Also note that the sizeToFit
current width of the label will be the maximum width, and the width will only be narrower and will not widen after execution.
For the NIB and Storyboard,mark Amery with Auto Layout, the solution is added in the comments:
If AutoLayout is used in the nib or storyboard, then the viewDidLoad
tune sizeToFit
is not working, because the actual order is to execute the viewDidLoad
AutoLayout first, the AutoLayout will be executed SizeToFit Results are overwritten.
But viewDidLayoutSubviews
it works in the sizeToFit
notes .
Answer 2: Add a newline at the end
Purple Ninja Girl, 44 likes
A simpler approach (and a dirty one) is to UILabel
set the line break mode to Clip
, and then add some newline directly at the end.
[displayString stringByAppendingString:"\n\n\n\n"];
This method is not omnipotent-especially if the text goes out of range and needs to be displayed at the end "...".
Answer 3: Use
UITextField
Replace
UILabel
Jowie, 47 likes
UITextField
instead UILabel
, the default is the top alignment. Can be userInterationEnabled
set to NO
so that it cannot scroll.
Answer 4: Rewrite
UILabel
Of
drawInRect
Method
Martin wickman,21 Praise
Create a UILabel
subclass that is very handy to use:
// TopLeftLabel.h#import <Foundation/Foundation.h>@interface TopLeftLabel : UILabel {}@end
topleftlabel.m#import"TopLeftLabel.h"@implementationtopleftlabel-(ID) initWithFrame: (CGRect) Frame {return [Super Initwithframe:frame];} - (CGRect) Textrectforbounds: (cgrect) bounds Limitedtonumberoflines: (NSInteger) NumberOfLines {cgrect textrect = [super textRectForBounds: Bounds Limitedtonumberoflines:numberoflines]; Textrect.origin.y = Bounds.Y; return Textrect;} -(void) Drawtextinrect: (cgrect) requestedrect {cgrect actualrect = [self textrectforbounds:requestedrect Limitedtonumberoflines:self.numberOfLines]; [super Drawtextinrect:actualrect];} @end
Wen/Dai Cang (Jane book author)
Original link: http://www.jianshu.com/p/429470186933
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".
Uilabel Top Alignment solution (reprint)