当前位置: 萬仟网 > IT编程>移动>IOS > (转)iOS学习——UIlabel设置行间距和字间距

(转)iOS学习——UIlabel设置行间距和字间距

28  人参与 | 时间:2019-01-04 | 我要评论

  在ios开发中经常会用到uilabel来展示一些文字性的内容,但是默认的文字排版会觉得有些挤,为了更美观也更易于阅读我们可以通过某些方法将uilabel的行间距和字间距按照需要调节。

  比如一个label的默认间距效果是这样:

然后用一个封装起来的category来调整这部分文字的行间距,其中5.0就是我自定义的文字间距:

[uilabel changelinespaceforlabel:cell.describelabel withspace:5.0];

调整后的效果是这样的:

这是一个uilabel 的category,他的内部实现是这样的:

uilabel+changelinespaceandwordspace.h

#import <uikit/uikit.h>

@interface uilabel (changelinespaceandwordspace)

/**
 *  改变行间距
 */
+ (void)changelinespaceforlabel:(uilabel *)label withspace:(float)space;

/**
 *  改变字间距
 */
+ (void)changewordspaceforlabel:(uilabel *)label withspace:(float)space;

/**
 *  改变行间距和字间距
 */
+ (void)changespaceforlabel:(uilabel *)label withlinespace:(float)linespace wordspace:(float)wordspace;

@end

uilabel+changelinespaceandwordspace.m

#import "uilabel+changelinespaceandwordspace.h"

@implementation uilabel (changelinespaceandwordspace)

+ (void)changelinespaceforlabel:(uilabel *)label withspace:(float)space {
    nsstring *labeltext = label.text;
    nsmutableattributedstring *attributedstring = [[nsmutableattributedstring alloc] initwithstring:labeltext];
    nsmutableparagraphstyle *paragraphstyle = [[nsmutableparagraphstyle alloc] init];
    [paragraphstyle setlinespacing:space];
    [attributedstring addattribute:nsparagraphstyleattributename value:paragraphstyle range:nsmakerange(0, [labeltext length])];
    label.attributedtext = attributedstring;
    [label sizetofit];
}

+ (void)changewordspaceforlabel:(uilabel *)label withspace:(float)space {
    nsstring *labeltext = label.text;
    nsmutableattributedstring *attributedstring = [[nsmutableattributedstring alloc] initwithstring:labeltext attributes:@{nskernattributename:@(space)}];
    nsmutableparagraphstyle *paragraphstyle = [[nsmutableparagraphstyle alloc] init];
    [attributedstring addattribute:nsparagraphstyleattributename value:paragraphstyle range:nsmakerange(0, [labeltext length])];
    label.attributedtext = attributedstring;
    [label sizetofit];
}

+ (void)changespaceforlabel:(uilabel *)label withlinespace:(float)linespace wordspace:(float)wordspace {
    nsstring *labeltext = label.text;
    nsmutableattributedstring *attributedstring = [[nsmutableattributedstring alloc] initwithstring:labeltext attributes:@{nskernattributename:@(wordspace)}];
    nsmutableparagraphstyle *paragraphstyle = [[nsmutableparagraphstyle alloc] init];
    [paragraphstyle setlinespacing:linespace];
    [attributedstring addattribute:nsparagraphstyleattributename value:paragraphstyle range:nsmakerange(0, [labeltext length])];
    label.attributedtext = attributedstring;
    [label sizetofit];
}

@end

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

◎已有 0 人评论

Copyright © 2019  萬仟网 保留所有权利. 粤ICP备17035492号-1
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com