给UILabel增加两端对齐能力

 使用类别的方式给UILabel增加两端对齐能力

1).h文件

#import


@interface UILabel (Alignment)


//两端对齐

- (void)textAlignmentLeftAndRight;


//指定Labelwidth两端对齐

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;


@end


2).m文件

#import"UILabel+Alignment.h"

#import


@implementation UILabel (Alignment)


- (void)textAlignmentLeftAndRight{

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

}


- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{

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

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

   NSNumber *number = [NSNumber  numberWithFloat:margin];

   NSMutableAttributedString *attribute = [[NSMutableAttributedString  alloc]  initWithString:self.text];

    [attribute  addAttribute:NSKernAttributeName  value:numberrange:NSMakeRange(0,self.text.length -1 )];

   self.attributedText = attribute;

}


@end


3)示例

#import"UILabel+Alignment.h"

- (void)viewDidLoad {

    [superviewDidLoad];

   // Do any additional setup after loading the view, typically from a nib.    

   UILabel  *label = [[UILabel  allocinitWithFrame:CGRectMake(40,200,200,30)];

    label.backgroundColor = [UIColor  greenColor];

    [self.view  addSubview:label];

    label.text =@"我两端对齐了啊";

    [label  textAlignmentLeftAndRight];

}




你可能感兴趣的:(技术Tips)