UILable 设置左右上下边距

2017-08-14  本文已影响157人  纯阳子_

1:自定义UILable
.h:

 @interface ContectLable : UILabel

// 用来决定上下左右内边距,也可以提供一个借口供外部修改,在这里就先固定写死
@property (assign, nonatomic) UIEdgeInsets edgeInsets;

@end

.m:

@implementation ContectLable

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
         self.edgeInsets = UIEdgeInsetsMake(0, 3, 0, 3);
    }
  return self;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 3, 0, 3);
    }
    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)];
}

@end

2: 自定义后,发现lable如果为自适应的话,就会显示不全,解决方法:

    [lable sizeToFit];
    lable.adjustsFontSizeToFitWidth =YES;

3:中划线

 NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
 NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"内容" attributes:attribtDic];
 label.attributedText = attribtStr;

4:下划线

 NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
 NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"内容" attributes:attribtDic];
 label.attributedText = attribtStr;
上一篇 下一篇

猜你喜欢

热点阅读