控制iOS中文字的字间距与行间距

时间:2023-02-01 08:29:29

为了满足不同的视觉效果,我们文字之间的字间距行间距,经常在项目中需要更改,今天把这几句代码提取出来,和小伙伴们一起分享,以免下次你找不到呦~

如果需要字间距需要提前写上 #import<CoreText/CoreText.h> ,而只需要行间距的话是不需要的。

如果引用不了的话,需要导入CoreText.framework这个库。


没有什么多说的直接上代码:

//
// ViewController.m
// TextSpacingExe
//
// Created by a111 on 16/4/20.
// Copyright © 2016年 司小文. All rights reserved.
//

#import "ViewController.h"
#import <CoreText/CoreText.h>


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self makeUI];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)makeUI{
NSString *infoStr = @"我是需要改变行间距与字间距的字符串,我是需要改变行间距与字间距的字符串,我是需要改变行间距与字间距的字符串";
UILabel *infoLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, self.view.frame.size.width-40, 100)];
infoLab.text = infoStr;
infoLab.numberOfLines = 0;
infoLab.textAlignment = NSTextAlignmentLeft;
infoLab.font = [UIFont systemFontOfSize:15.];
infoLab.userInteractionEnabled = YES;

//实例化NSMutableAttributedString模型
NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:infoStr];

//建立行间距模型
NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];

//设置行间距
[paragraphStyle1 setLineSpacing:5.f];

//把行间距模型加入NSMutableAttributedString模型
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [infoStr length])];

//设置字间距
long number = 5.f;

//CFNumberRef添加字间距
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); [attributedString1 addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[attributedString1 length])];

//清除CFNumberRef
CFRelease(num);

//给lab赋值改变好的文字
[infoLab setAttributedText:attributedString1];

//让lab内部自适应大小
[infoLab sizeToFit];

[self.view addSubview:infoLab];

}

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

@end


效果图:

控制iOS中文字的字间距与行间距



参考实例:

https://yunpan.cn/cPfmVNMZQk6vB (提取码:378a)


感谢观看,学以致用更感谢~