UILabel设置的固定的2行高度,但是一行时候显示在中间,两行的在上面 如图:

看起来就很丑,产品肯定是不让的,优化时候看到了一个好的文章正好可以解决这个问题
地址
亲测有效 代码在下面

.m代码
#import "TwoLineCenterLabel.h"
@implementation TwoLineCenterLabel
- (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:
// 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
.h代码
#import <UIKit/UIKit.h>
typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
NS_ASSUME_NONNULL_BEGIN
@interface TwoLineCenterLabel : UILabel
{
@private
VerticalAlignment _verticalAlignment;
}
@property (nonatomic) VerticalAlignment verticalAlignment;
@end
NS_ASSUME_NONNULL_END
使用时UILabel继承TwoLineCenterLabel就可以使用了
可以设置不同属性满足不同需求
//放到顶部
[label setVerticalAlignment:VerticalAlignmentTop];
//放到中间
// [label setVerticalAlignment:VerticalAlignmentMiddle];
//放到最下面
// [label setVerticalAlignment:VerticalAlignmentBottom];
网友评论