Reprinted from http://devtang.com/blog/2011/11/20/set-uilabel-text-align-top/Method one
When displaying text, first calculate how wide and how high the current text is displayed, and then change the size of the corresponding Uilabel to the corresponding width and height. The phase of this method is as follows:
When displaying text, first calculate how wide and how high the current text is displayed, and then change the size of the corresponding Uilabel to the corresponding width and height. The phase of this method is as follows:
12345678 |
CgsizeMaximumSize=Cgsizemake(300,9999);NSString*DateString=@ "The date today is January 1st, 1999";Uifont*Datefont=[UifontFontwithname:@ "Helvetica"Size14];CgsizeDatestringsize=[DateStringSizewithfont:Datefont constrainedtosize:maximumsize Linebreakmode:self. Datelabel. Linebreakmode; cgrect dateframe = CGRectMake< Span class= "P" > (1010300< Span class= "P", datestringsize. Height); self. Datelabel. Frame = dateframe;
|
Method Two
This method is more simple and rude, but effective. The method is to add more \ n after the text. It is important to note that after \ n is added at least one space, otherwise the extra \ n will be ignored by Uilabel. From this point of view, Uilabel seems to be too "smart".
The method is as follows:
The code for this method is as follows:
12 |
for (int i=0i<newlinestopadi++) self.< span class= "n" >text = [self. Text stringbyappendingstring:@ "\n" ; |
Method Three
The most orthodox method, using the OBJECTIVE-C category feature, modifies the Uilabel drawing code. The sample code is as follows:
12345< Span class= "Line-number" >6789< Span class= "Line-number" >10111213 141516 17181920 212223 24252627 2829 |
--File:uilabel+verticalalign.h#pragma Mark VerticalAlign@interfaceUILabel(verticalalign)-(void)AlignTop;-(void)AlignBottom;@end--FILE:UILABEL+VERTICALALIGN.M@implementationUILabel(verticalalign)-(void)AlignTop{ CgsizeFontSize=[Self.TextSizewithfont:Self.Font]; DoubleFinalheight=FontSize.Height*Self.NumberOfLines; DoubleFinalwidth=Self.Frame.Size.Width;Expected width of label CgsizeThestringsize=[Self.TextSizewithfont:Self.FontConstrainedtosize:Cgsizemake(Finalwidth,Finalheight)Linebreakmode:Self.Linebreakmode]; IntNewlinestopad=(Finalheight-Thestringsize.Height)/FontSize.Height; For(IntI=0;I<Newlinestopad;I++) Self.Text=[Self.TextStringbyappendingstring:@"\ n"];}-(void)AlignBottom{ CgsizeFontSize=[Self.TextSizewithfont:Self.Font]; DoubleFinalheight=FontSize.Height*Self.NumberOfLines; DoubleFinalwidth=Self.Frame.Size.Width;Expected width of label CgsizeThestringsize=[Self.TextSizewithfont:Self.FontConstrainedtosize:Cgsizemake(Finalwidth,Finalheight)Linebreakmode:Self.Linebreakmode]; IntNewlinestopad=(Finalheight-Thestringsize.Height)/FontSize.height; for (int i=0< Span class= "P"; i<newlinestopadi++) self.< span class= "n" >text = [nsstring stringwithformat: @ "\n%@" ,selftext} @end
|
Align top of uilabel text