需求:
- 限制两行,超出部分显示省略号...
- 要求自动居上对齐
实现方案:
- 文本后面加多一些\n
- 修改高度
- 重新绘制UILabel
第一种方式会导致不再显示省略号,第二种方式需要每次使用时计算文字占用高度不方便。所以最后我使用第三种方式实现:
.h文件中声明一个枚举类型用来设置对齐方式:
typedef enum {
VerticalAlignmentTop = 0, //default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@property (nonatomic, assign) VerticalAlignment verticalAlignment;
.m中实现设置对齐方法:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.verticalAlignment = VerticalAlignmentMiddle;
}
return self;
}
- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
_verticalAlignment = verticalAlignment;
[self setNeedsLayout];
}
- (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];
}