Paste_Image.png
問題說明
默認(rèn)Label的顯示效果如下

很多情況下捞蛋,需要如下有內(nèi)邊距的效果(注意第一行與最后一行文字與label的上下邊距
)

解決方案
為了解決這個(gè)問題,設(shè)計(jì)SFLabel如下洞坑,繼承自UILabel
#import "SFLabel.h"
#import <UIKit/UIKit.h>
@interface SFLabel ()
// 用來決定上下左右內(nèi)邊距,也可以提供一個(gè)借口供外部修改,在這里就先固定寫死
@property (assign, nonatomic) UIEdgeInsets edgeInsets;
@end
@implementation SFLabel
//下面三個(gè)方法用來初始化edgeInsets
- (instancetype)initWithFrame:(CGRect)frame
{
if(self = [super initWithFrame:frame])
{
self.edgeInsets = UIEdgeInsetsMake(25, 0, 25, 0);
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
self.edgeInsets = UIEdgeInsetsMake(25, 0, 25, 0);
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
self.edgeInsets = UIEdgeInsetsMake(25, 0, 25, 0);
}
// 修改繪制文字的區(qū)域颗祝,edgeInsets增加bounds
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
/*
調(diào)用父類該方法
注意傳入的UIEdgeInsetsInsetRect(bounds, self.edgeInsets),bounds是真正的繪圖區(qū)域
*/
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,
self.edgeInsets) limitedToNumberOfLines:numberOfLines];
//根據(jù)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
{
//令繪制區(qū)域?yàn)樵紖^(qū)域恼布,增加的內(nèi)邊距區(qū)域不繪制
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
@end
將UIlabel的類型改為SFLabel螺戳,看看現(xiàn)在效果是否如第二幅圖??。
注意事項(xiàng)
- 通過SFLabel中的方法修改UILabel的內(nèi)邊距最好只修改上下內(nèi)邊距折汞,通過系統(tǒng)NSMutableParagraphStyle可以修改左邊內(nèi)邊距倔幼;
- 通過
boundingRectWithSize:options:attributes:context:
計(jì)算SFLabel內(nèi)容計(jì)算出的區(qū)域仍然是與直接使用UILabel的結(jié)果一樣,因此需要小心使用爽待,可以在boundingRectWithSize:options:attributes:context:
基礎(chǔ)上根據(jù)edgeInsets進(jìn)行修正损同。