iOS - lable文字固定宽度 等间距

调用

#import "UILabel+XMarginCategry.h"
    [self.nameLabel textAlignmentLeftAndRight];
    [self.nameLabel textAlignmentLeftAndRightWith:nameLabelW];

.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface UILabel (XMarginCategry)
//两端对齐

- (void)textAlignmentLeftAndRight;

//指定Label以最后的冒号对齐的width两端对齐

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;


@end

NS_ASSUME_NONNULL_END

.m


#import "UILabel+XMarginCategry.h"
#import 
@implementation UILabel (XMarginCategry)
- (void)textAlignmentLeftAndRight{

[self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];

}

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{

    if(self.text==nil||self.text.length==0) {

        return;

    }

    CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;

    NSInteger length = (self.text.length-1);

    NSString* lastStr = [self.text substringWithRange:NSMakeRange(self.text.length-1,1)];

    if([lastStr isEqualToString:@":"]||[lastStr isEqualToString:@":"]) {

        length = (self.text.length-2);

    }

    CGFloat margin = (labelWidth - size.width)/length;

    NSNumber*number = [NSNumber numberWithFloat:margin];

    NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0,length)];
//    [attribute addAttribute: value:number range:NSMakeRange(0,length)];

    self.attributedText= attribute;

}


@end

你可能感兴趣的:(iOS - lable文字固定宽度 等间距)