iOS開發(fā)中會遇到label展示漢字和漢字標點符號導(dǎo)致無法右端對齊,或兩端對齊的解決方法
類似這種,需求是圖中上面部分,但是展示效果是下面一部分,這個效果其實很簡單,label的text只能設(shè)置左對齊或右對齊或者居中,但是是label的attributedText屬性可以設(shè)置兩端對齊方式,這樣排列漢字的時候看起來非常整齊,效果杠杠的。
不多說了,直接上代碼
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, 300, 280, 200)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:16.0];
label.textColor = [UIColor grayColor];
NSString*str=@"測試行間距,測試兩端對齊,測試行間距,測試兩端對齊,測試行間距,測試兩端對齊,測試行間距,測試兩端對齊,測試行間距,測試兩端對齊,測試行間距,測試兩端對齊,";
NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
//設(shè)置label每行文字之間的行間距
//paragraphStyle1.lineSpacing=8;
//設(shè)置文字兩端對齊
paragraphStyle1.alignment=NSTextAlignmentJustified;
NSDictionary * dic =@{
//這兩個一定要加哦。否則就沒效果啦
NSParagraphStyleAttributeName:paragraphStyle1,
NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleNone],
//以下可以按需求添加啦,還有其余的可以自己添加
NSFontAttributeName:[UIFont systemFontOfSize:16.0]
};
[attributedString1 setAttributes:dic range:NSMakeRange(0, attributedString1.length)];
[label setAttributedText:attributedString1];
[self.view addSubview:label];
友情提示:如果遇到漢語字符串中,帶有英文字母或者數(shù)字的時候,會自動折行,這種情況下,只需要設(shè)置label的一個屬性就好啦:label.lineBreakMode = NSLineBreakByCharWrapping;