The Uilabel property of the iOS system frame textalignment only adjusts horizontally to the center, left and right, without vertical adjustment. Therefore, to customize a class that inherits from Uilabel, the text is redrawn in the implementation file of the class, and the vertical orientation is adjusted.
Create a new class file that inherits from Uilabel, and the header file is as follows:
#import <uikit/uikit.h>typedef Ns_enum (nsinteger,verticalalignment) { verticalalignmenttop, Verticalalignmentmiddle, Verticalalignmentbottom}; @interface Fsverticallyalignedlabel:uilabel@property ( nonatomic,assign) VerticalAlignment VerticalAlignment; @end
In the. m file, implement the VerticalAlignment setting method
@implementation fsverticallyalignedlabel-(ID) initWithFrame: (CGRect) frame{if (self = [Super Initwithframe:frame]) { Self.verticalalignment = Verticalalignmentmiddle; } return self;} /** * Set Property method * * @param verticalalignment vertically adjust position */-(void) Setverticalalignment: (verticalalignment) verticalalignment{ _verticalalignment = VerticalAlignment; [Self setneedsdisplay];} /** * Calculates the rectangle area of the text * * @param bounds label Rectangle area * @param numberoflines number of lines * * @return returns the rectangular area occupied by the text */-(cgrect) textr Ectforbounds: (CGRect) Bounds Limitedtonumberoflines: (nsinteger) numberoflines{cgrect textrect = [super Textrectforbounds:bounds Limitedtonumberoflines:numberoflines]; Adjust the vertical position by setting the Y value of the font area switch (self.verticalalignment) {Case VERTICALALIGNMENTTOP:TEXTRECT.ORIGIN.Y = BOUNDS.ORIGIN.Y; Break Case VERTICALALIGNMENTMIDDLE:TEXTRECT.ORIGIN.Y = bounds.origin.y + (bounds.size.height-textrect.size.height) /2.0;Break Case VERTICALALIGNMENTBOTTOM:TEXTRECT.ORIGIN.Y = bounds.origin.y + bounds.size.height-textrect.size.height; Break } return textrect;} Overriding the parent class method-(void) Drawtextinrect: (cgrect) rect{cgrect actualrect = [self textrectforbounds:rect limitedtonumberoflines: Self.numberoflines]; [Super Drawtextinrect:actualrect];} @end
Custom Uilabel Set the vertical direction of the home, centered, in the bottom