---
title: "[ios]label增加边距-既左右对齐"
author: "119568242"
date: "2014-07-09T01:23:56Z"
tags: []
categories: ["移动开发"]
slug: "ios-label"
draft: false
lastmod: "2014-07-09T01:23:56Z"
id: 2089782
url: "https://poolo.iteye.com/blog/2089782"
---

http://www.cocoachina.com/bbs/read.php?tid=189979&page=2

 

谢谢各位了，找到问题的原因所在了。在NSAttributeString中找到了这句话。默认用来计算的字体和大小。  
UIKIT\_EXTERN NSString \*const NSFontAttributeName NS\_AVAILABLE\_IOS(6\_0);                // UIFont, default Helvetica(Neue) 12

吃亏就在这了，在所有计算方法里需要用到attributes这个参数的时候我都传nil，导致计算的大小和UILabel默认的字体大小不一致，计算出错。  
附上我的最终效果和代码。

[?](http://www.cocoachina.com/bbs/)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

`UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 21)];`

`label.backgroundColor = [UIColor orangeColor];`

`[self.view addSubview:label];`

`    ` 

`NSMutableAttributedString` `*attributeString = [[NSMutableAttributedString` `alloc] initWithString:@"TViewController"];`

`//计算文字大小，参数一定要符合相应的字体和大小`

`CGSize attributeSize = [attributeString.string sizeWithAttributes:@{NSFontAttributeName:label.font}];`

`//计算字符间隔`

`CGSize frame = label.frame.size;`

`NSNumber` `*wordSpace = [NSNumber` `numberWithInt:(frame.width-attributeSize.width)/(attributeString.length-1)];`

`//添加属性`

`[attributeString addAttribute:NSKernAttributeName` `value:wordSpace range:NSMakeRange(0, attributeString.length)];`

`   ` 

`label.attributedText = attributeString;`

图片:QQ20140311-1@2x.png   
![](http://www.cocoachina.com/bbs/attachment/Fid_6/6_159909_b843b8318422444.png)