美文网首页
iOS - lable文字固定宽度 等间距

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

作者: HanZhiZzzzz | 来源:发表于2022-06-01 10:08 被阅读0次

    调用

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

    .h

    #import <UIKit/UIKit.h>
    
    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 <CoreText/CoreText.h>
    @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文字固定宽度 等间距

          本文链接:https://www.haomeiwen.com/subject/mdcxmrtx.html