iOS设置UILabel行距和调整间距

1.建UILabel分类

#import 

@interface UILabel (extension)

/**
 *  设置字间距
 */
- (void)setColumnSpace:(CGFloat)columnSpace;
/**
 *  设置行距
 */
- (void)setRowSpace:(CGFloat)rowSpace;

@end
----------------------------------------------------------------------------------

#import "UILabel+extension.h"
#import 

@implementation UILabel (extension)

- (void)setColumnSpace:(CGFloat)columnSpace
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    //调整间距
    [attributedString addAttribute:(__bridge NSString *)kCTKernAttributeName value:@(columnSpace) range:NSMakeRange(0, [attributedString length])];
    self.attributedText = attributedString;
}

- (void)setRowSpace:(CGFloat)rowSpace
{
    self.numberOfLines = 0;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    //调整行距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = rowSpace;
    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attributedString;
}

@end

2.在ViewController调用

#import "ViewController.h"
#import "UILabel+extension.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.label.backgroundColor = [UIColor orangeColor];
    self.label.text = @"12dhjskafheuwfhsakfb12dhjskafheuwfhsakfb12dhjskafheuwfhsakfb12dhjskafheuwfhsakfb12dhjskafheuw";
    //当设置了UILabel的attributedText属性时textAlignment会失效  可以通过NSMutableParagraphStyle的baseWritingDirection这个属性来实现
    self.label.textAlignment = NSTextAlignmentLeft;
    self.label.numberOfLines = 0;
    [self.label setColumnSpace:5];
    [self.label setRowSpace:20];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(iOS设置UILabel行距和调整间距)