In iOS default Uilabel text in the vertical direction can only center alignment, Bo Master reference foreign sites, from the Uilabel inherit a new class, to achieve the alignment of the home, the center alignment, the bottom of the alignment. Specific as follows:
[CPP]View Plaincopy
- //
- MyUILabel.h
- //
- //
- Created by yexiaozi_007 on 3/4/13.
- Copyright (c) yexiaozi_007. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- typedef ENUM
- {
- Verticalalignmenttop = 0, //default
- Verticalalignmentmiddle,
- Verticalalignmentbottom,
- } VerticalAlignment;
- @interface Myuilabel:uilabel
- {
- @Private
- VerticalAlignment _verticalalignment;
- }
- @property (nonatomic) VerticalAlignment verticalalignment;
- @end
[CPP]View Plaincopy
- //
- myuilabel.m
- //
- //
- Created by yexiaozi_007 on 3/4/13.
- Copyright (c) yexiaozi_007. All rights reserved.
- //
- #import "MyUILabel.h"
- @implementation Myuilabel
- @synthesize verticalalignment = Verticalalignment_;
- -(ID) initWithFrame: (CGRect) Frame {
- if (self = [Super Initwithframe:frame]) {
- Self.verticalalignment = Verticalalignmentmiddle;
- }
- return self;
- }
- -(void) Setverticalalignment: (verticalalignment) VerticalAlignment {
- Verticalalignment_ = VerticalAlignment;
- [Self setneedsdisplay];
- }
- -(CGRect) Textrectforbounds: (cgrect) Bounds Limitedtonumberoflines: (Nsinteger) NumberOfLines {
- CGRect textrect = [Super Textrectforbounds:bounds limitedtonumberoflines:numberoflines];
- switch (self.verticalalignment) {
- Case Verticalalignmenttop:
- TEXTRECT.ORIGIN.Y = BOUNDS.ORIGIN.Y;
- Break ;
- Case Verticalalignmentbottom:
- TEXTRECT.ORIGIN.Y = Bounds.origin.y + bounds.size.height-textrect.size.height;
- Break ;
- Case Verticalalignmentmiddle:
- //Fall through.
- Default:
- TEXTRECT.ORIGIN.Y = Bounds.origin.y + (bounds.size.height-textrect.size.height)/2.0;
- }
- return textrect;
- }
- -(void) Drawtextinrect: (CGRect) Requestedrect {
- CGRect actualrect = [self textrectforbounds:requestedrect limitedToNumberOfLines:self.numberOfLines];
- [Super Drawtextinrect:actualrect];
- }
- @end
When in use:
[CPP]View Plaincopy
- lbl_mylabel = [[myuilabel alloc] Initwithframe:cgrectmake (20, 50, 150, 600)];
- uicolor *color = [uicolor colorwithpatternimage:[uiimage imagenamed:@ "HalfTransparent.png" ]]; //use a translucent picture as the background color of the label
- LBL_MYLABEL.BACKGROUNDCOLOR&NBSP;=&NBSP;COLOR;&NBSP;&NBSP;
- lbl_mylabel.textalignment = uitextalignmentleft;
- LBL_MYLABEL.TEXTCOLOR&NBSP;=&NBSP;UICOLOR.WHITECOLOR;&NBSP;&NBSP;
- lbl_mylabel.linebreakmode = uilinebreakmodewordwrap;
- LBL_MYLABEL.NUMBEROFLINES&NBSP;=&NBSP;0;&NBSP;&NBSP;
- [lbl_mylabel setverticalalignment:verticalalignmenttop];
- [SELF&NBSP;ADDSUBVIEW:LBL_MYLABEL];&NBSP;