UIlabel文字两边对齐
2017-11-10 11:34 dengchaojie_learner 阅读(1055) 评论(0) 编辑 收藏 举报iOS开发 UIlabel 文字两边对齐
思路:算出每个字符之间的宽度
给UIlabel添加一个分类即可,代码如下:
* 必须导入这个头文件:CoreText/CoreText.h
- (void)changeAlignmentRightandLeft{
CGRect textSize = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : self.font} context:nil];
CGFloat margin = (self.frame.size.width - textSize.size.width) / (self.text.length - 1);// 每个字符之间,平均的宽度(点坐标)
NSNumber *number = [NSNumber numberWithFloat:margin];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:self.text];
[attributeString addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, self.text.length - 1)];
self.attributedText = attributeString;
}
http://blog.csdn.net/u013094208/article/details/52777225