新建一个继承与UIlable的类如图:
创建myUILabel类新建一个枚举表示(废话不说直接上代码)
typedef enum
{
VerticalAlignmentTop = 0,
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
#import "myUILabel.h"里面代码如下
#importtypedef enum
{
VerticalAlignmentTop = 0,
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@interface myUILabel : UILabel{
@private
VerticalAlignment _verticalAlignment;
}
@property (nonatomic) VerticalAlignment verticalAlignment;
@end
#import "myUILabel.m"里面代码如下
#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:
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
在使用的时候只需要如下创建即可([demoLable setVerticalAlignment:VerticalAlignmentTop];)
myUILabel*demoLable=[[myUILabel alloc]initWithFrame:CGRectMake(ScaleX(15), CGRectGetMaxY(lineView2.frame)+ScaleX(5),ScaleX(80), ScaleX(25) )];
[demoLable setVerticalAlignment:VerticalAlignmentTop];//让label居上显示
demoLable=[UIColor colorWithHexString:@"#666666"];
demoLable.textAlignment=NSTextAlignmentLeft;
demoLable.font=[UIFont systemFontOfSize:mytextfont];
demoLable.text=@"项目地址:";
// AddressLable.backgroundColor=[UIColor purpleColor];
[self addSubview:demoLable];
网友评论