First create a new. h file in Xcode and copy the following code in
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{@ Privateverticalalignment _verticalalignment;} @property (nonatomic) verticalalignment verticalalignment; @end
To create a new. m file, copy the following code into the
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 = Vertica Lalignmentmiddle; } 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
If this is the first. m file that you imported, Xcode will prompt you to create a bridging-header, select OK
Copy the code below into the newly created Bridging-header file.
#import "MyUILabel.h"
Then open your storyboard, click on the label you want to change the way to it, and change its class to Myuilabel, as follows
Then right-drag the label or left-click the command key to drag the line to the label's parent view's class to generate the outlet, if it was already connected, then after the custom class is changed, Change the Uilabel in the line generation code to Myuilabel, as follows
Then you can call the label's class method
Label.verticalalignment = Verticalalignmentbottom
According to the above code can be achieved in the next to it, the center of the code in the bottom changed to middle and top, the default is the
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A line of code implemented in the SWIFT Environment Uilabel aligned in the center