Uilabelz subclass-vertical arbitrary text alignment
14:22:25 | category: iPhone
Develop | font size subscription
Someone asked how to align the uilabel text correctly. They need uilabel to accommodate multiple lines of text, but they also need to adjust the text. The problem they encounter is that the single line of text is always centered and aligned in the vertical direction.
On the apple Forum:
Http://discussions.apple.com/thread.jspa? Threadid = 1759957 the uilabel subclass provided by someone can solve this problem:
This subclass is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Label2.h // (C) 2009 Ivan Misuno, www. cuberoom. Biz <br>
# ImpORT <uikit/uikit. h>Typedef Enum { Verticalalignmenttop = 0,// Default Verticalignmentmiddle, Verticalignmentbottom, } Verticalalignment;
@ Interface label2: uilabel { @ Private Verticalalignment _ verticalignment; }
@ Property (nonatomic) verticalignment;
@ End |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
// Label2.mm // (C) 2009 Ivan Misuno, www. cuberoom. biz
# ImpOrt "label2.h"
@ Implementation label2
-(ID) initwithframe :( cgrect) Frame { Self = [Super initwithframe: frame]; If (! Self) Return Nil;
_ Verticalalignment = verticalignmenttop; Return self; }
-(Void) dealloc { [Super dealloc]; }
-(Verticalignment) verticalignment { 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 |
You can use label2 where uilabel is used. You can set setverticalignment to verticalignmenttop, verticalignmentmiddle, or verticalignmentbottom to align the text to the top, center, or bottom. Very convenient!
Original article: uilabel subclass-align the text how you want!