iOS自定义 UILabel可以使文字居上 居中 居下

2017-09-25  本文已影响0人  冯龙胜

前言:做过iOS 的都知道,UILabel有让文字居左,居右,居中的属性,可是有时候我们在做项目的时候,可能会需要将label上的文字居上, 居中或者 居下这样的操作。那么今天我们就来说一说这种效果的实现方式。

#import <UIKit/UIKit.h>

typedefenum

{

VerticalAlignmentTop =0,// default

VerticalAlignmentMiddle,

VerticalAlignmentBottom,

} VerticalAlignment;

@interfaceBaseUILabel :UILabel

{

@private

VerticalAlignment_verticalAlignment;

}

@property(nonatomic)VerticalAlignmentverticalAlignment;

@end

#import"BaseUILabel.h"

@implementationBaseUILabel

@synthesizeverticalAlignment =verticalAlignment_;

- (id)initWithFrame:(CGRect)frame {

if(self= [superinitWithFrame:frame]) {

self.verticalAlignment=VerticalAlignmentMiddle;

}

returnself;

}

- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {

verticalAlignment_= verticalAlignment;

[selfsetNeedsDisplay];

}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {

CGRecttextRect = [supertextRectForBounds:boundslimitedToNumberOfLines:numberOfLines];

switch(self.verticalAlignment) {

caseVerticalAlignmentTop:

textRect.origin.y= bounds.origin.y;

break;

caseVerticalAlignmentBottom:

textRect.origin.y= bounds.origin.y+ bounds.size.height- textRect.size.height;

break;

caseVerticalAlignmentMiddle:

// Fall through.

default:

textRect.origin.y= bounds.origin.y+ (bounds.size.height- textRect.size.height) /2.0;

}

returntextRect;

}

-(void)drawTextInRect:(CGRect)requestedRect {

CGRectactualRect = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];

[superdrawTextInRect:actualRect];

}

@end

这样我们在使用的时候,只要继承这个label类,然后选择想要实现效果的属性即可

上一篇 下一篇

猜你喜欢

热点阅读