UILabel添加UIEdgeInsets
@interface WSFLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(8, 8+2, 8, 8+2);
}
return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
UIEdgeInsets insets = self.edgeInsets;
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets) limitedToNumberOfLines:numberOfLines];
rect.origin.x -= insets.left;
rect.origin.y -= insets.top;
rect.size.width += (insets.left + insets.right);
rect.size.height += (insets.top + insets.bottom);
return rect;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
UILabel自适应高度
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
UILabel自适应宽度
[label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
抗拉伸和抗压缩
// 抗被拉伸
[self.label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
// 抗被压缩
[self.label setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];