一、自定义Label,设置内边距
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface PaddingLabel : UILabel
@end
NS_ASSUME_NONNULL_END
#import "PaddingLabel.h"
@interface PaddingLabel ()
@property (assign, nonatomic) UIEdgeInsets edgeInsets;
@end
@implementation PaddingLabel
- (void)awakeFromNib {
[super awakeFromNib];
self.edgeInsets = UIEdgeInsetsMake(5, 10, 5, 10);
}
// 修改绘制文字的区域,edgeInsets增加bounds
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
/*
调用父类该方法
注意传入的UIEdgeInsetsInsetRect(bounds, self.edgeInsets),bounds是真正的绘图区域
*/
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,
self.edgeInsets) limitedToNumberOfLines:numberOfLines];
//根据edgeInsets,修改绘制文字的bounds
rect.origin.x -= self.edgeInsets.left;
rect.origin.y -= self.edgeInsets.top;
rect.size.width += self.edgeInsets.left + self.edgeInsets.right;
rect.size.height += self.edgeInsets.top + self.edgeInsets.bottom;
return rect;
}
//绘制文字
- (void)drawTextInRect:(CGRect)rect {
if (self.text && ![self.text isEqualToString:@""]) {
//令绘制区域为原始区域,增加的内边距区域不绘制
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
self.hidden = NO;
} else {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, UIEdgeInsetsZero)];
self.hidden = YES;
}
}
@end
二、自定义Label,设置行间距
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LineSpaceLabel : CommonLabel
@property (nonatomic, assign) CGFloat lineSpace;
@end
NS_ASSUME_NONNULL_END
#import "LineSpaceLabel.h"
@implementation LineSpaceLabel
- (void)setLineSpace:(CGFloat)lineSpace {
_lineSpace = lineSpace;
self.attributedText = [self.text attributedStringWithLineSpace:lineSpace];
}
- (void)setText:(NSString *)text {
self.attributedText = [text attributedStringWithLineSpace:self.lineSpace];
}
- (void)awakeFromNib {
[super awakeFromNib];
self.lineSpace = 5;
}
@end
设置NSAttributedString方法,参考https://blog.csdn.net/qq_25639809/article/details/89643192
#pragma mark - NSAttributedString
- (NSAttributedString *)attributedStringWithLineSpace:(CGFloat)lineSpace {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = lineSpace;
NSRange range = NSMakeRange(0, self.length);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
return attributedString;
}