iOS-设置UILabel文本靠最顶部展示
Posted MinggeQingchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS-设置UILabel文本靠最顶部展示相关的知识,希望对你有一定的参考价值。
UILabel中只有设置文本横向靠左,居中,靠右显示,属性如下:
@property(nonatomic) NSTextAlignment textAlignment; // default is NSTextAlignmentNatural (before ios 9, the default was NSTextAlignmentLeft)
但是想让文本垂直顶部,或者底部展示,是没有这个属性的,因此需要重写UILabel,首先创建一个BZAlertLabel继承UILabel,方法如下:
BZAlertLabel.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@interface BZAlertLabel : UILabel
@property (nonatomic, assign) VerticalAlignment verticalAlignment;
@end
NS_ASSUME_NONNULL_END
BZAlertLabel.m文件
#import "BZAlertLabel.h"
@interface BZAlertLabel ()
@end
@implementation BZAlertLabel
- (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
以上是关于iOS-设置UILabel文本靠最顶部展示的主要内容,如果未能解决你的问题,请参考以下文章
iOS--UILabel设置行距和字间距,并根据文本计算高度