iOS开发 UIlabel 文字两边对齐
思路:算出每个字符之间的宽度
给UIlabel添加一个分类即可,代码如下:
* 必须导入这个头文件:CoreText/CoreText.h
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #000000; background-color: #fffcea }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #000000; background-color: #fffcea; min-height: 16.0px }
span.s1 { color: #ba2da2 }
span.s2 { color: #703daa }
span.s3 { color: #78492a }
span.s4 { color: #272ad8 }
span.s5 { color: #3e1e81 }
- (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