在iOS開發中經常會用到UIlabel來展示一些文字性的內容,但是預設的文字排版會覺得有些擠,為了更美觀也更易於閱讀我們可以通過某些方法將UIlabel的行間距和字間距按照需要調節。 比如一個Label的預設間距效果是這樣: 然後用一個封裝起來的Category來調整這部分文字的行間距,其中5.0就 ...
在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