设置lab字间距,简单方便实用

来源:互联网 发布:电脑速录软件 编辑:程序博客网 时间:2024/05/11 16:05

转载文章,原文地址:http://blog.csdn.net/siwen1990 转载

今天做项目刚好需求里要调整lab间距,保证效果美观,网上搜了下,发现一篇不错的文章,很实用也很简单,粘上来供需要之人使用。

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

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