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

本文介绍如何在iOS开发中调整文字的字间距和行间距,并提供了代码示例及应用效果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

如果需要字间距需要提前写上 #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


效果图:




参考实例:

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


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




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值