设置富文本字间距,文字不能居中对齐

最近有一个需求,需要设置一个UILabel的字间距,我马上就想到了富文本,于是就写了下面的代码

1
2
3
4
5
NSString *str = self.label.text;
NSDictionary *attribute = @{NSKernAttributeName:@(10),
NSFontAttributeName:[UIFont systemFontOfSize:15]};
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:str attributes:attribute];
self.label.attributedText = attStr;

其中NSKernAttributeName属性就是设置文字的字间距。但是,现在就有一个问题,设置字间距后,原本居中显示的文字,不能居中显示了。

这是我设置字间距之前的label

1

这是我设置了字间距后的label

2

“你”字距左边距明显要比”鸿”字的右边距要大。

经过一阵Google,在StackOverflow上找到了相同的问题,链接是http://stackoverflow.com/questions/23741850/nsstring-drawinrectwithattributes-not-correctly-centered-when-using-nskernattr,根据问题回答里的做法,我把代码做了修改,如下:

1
2
3
4
5
NSString *str = self.label.text;
NSMutableAttributedString *mutAttStr = [[NSMutableAttributedString alloc] initWithString:str];
[mutAttStr addAttribute:NSKernAttributeName value:@(10) range:NSMakeRange(0, str.length - 1)];
[mutAttStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, str.length)];
self.label.attributedText = [mutAttStr copy];

修改后效果如下:

3