这里我们创建一个继承自UILabel的子类 HJLabel
- HJLabel.h
//
// HJLabel.h
// UILabelTest
//
// Created by 黄健 on 16/5/25.
// Copyright © 2016年 黄健. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum {
HJTextVerticalAlignmentTop,
HJTextVerticalAlignmentMiddle,
HJTextVerticalAlignmentBottom,
} HJTextVerticalAlignment;
@interface HJLabel : UILabel
/**
* @author 黄健, 2016-05-25 20:05:54
*
* @brief 设置label的垂直对齐方式,包括顶部对齐、居中对齐和底部对齐
*/
@property (nonatomic, assign) HJTextVerticalAlignment textVerticalAlignment;
@end
- HJLabel.m
//
// HJLabel.m
// UILabelTest
//
// Created by 黄健 on 16/5/25.
// Copyright © 2016年 黄健. All rights reserved.
//
#import "HJLabel.h"
@implementation HJLabel
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
self.textVerticalAlignment = HJTextVerticalAlignmentMiddle;
}
return self;
}
- (void)setTextVerticalAlignment:(HJTextVerticalAlignment)textVerticalAlignment
{
_textVerticalAlignment = textVerticalAlignment;
[self setNeedsDisplay];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
switch (self.textVerticalAlignment)
{
case HJTextVerticalAlignmentTop:
textRect.origin.y = bounds.origin.y;
break;
case HJTextVerticalAlignmentBottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
break;
case HJTextVerticalAlignmentMiddle:
// 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
- 测试
#define content1 @"红尘之上,浮生若梦,一帘忧思,一缕情思,邂逅相逢转角遇见爱,奈何几时寻得有缘人。"
HJLabel *myLabel = [[HJLabel alloc] init];
myLabel.frame = CGRectMake(35, 450, 250, 80);
myLabel.backgroundColor = [UIColor cyanColor];
myLabel.text = content1;
myLabel.numberOfLines = 0;
myLabel.font = [UIFont systemFontOfSize:14];
myLabel.textVerticalAlignment = HJTextVerticalAlignmentTop;
[self.view addSubview:myLabel];
- 运行
小技能:获取文本内容实际占用的尺寸
以上面的测试代码为例,追加以下代码
NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:14]};
/**
* @author 黄健, 2016-05-26 10:05:44
*
* @brief 获取文字内容的实际宽高
*
* @param 250 指定宽度
* @param MAXFLOAT 高度任意
*
* @return 返回计算后得到的宽高
*/
CGSize contentSize = [content1 boundingRectWithSize:CGSizeMake(250, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
NSLog(@"实际宽高:%@", NSStringFromCGSize(contentSize)); // {238, 50.12109375}
- 运行