iOS UILabel两端对齐的实现(可包括中英文/数字)
- (void)conversionCharacterInterval:(NSInteger)maxInteger current:(NSString *)currentString withLabel:(UILabel *)label { CGRect rect = [[currentString substringToIndex:1] boundingRectWithSize:CGSizeMake(200,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: label.font} context:nil]; NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:currentString]; float strLength = [self getLengthOfString:currentString]; [attrString addAttribute:NSKernAttributeName value:@(((maxInteger - strLength) * rect.size.width)/(strLength - 1)) range:NSMakeRange(0, strLength)]; label.attributedText = attrString; } - (float)getLengthOfString:(NSString*)str { float strLength = 0; char *p = (char *)[str cStringUsingEncoding:NSUnicodeStringEncoding]; for (NSInteger i = 0 ; i < [str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) { if (*p) { strLength++; } p++; } return strLength/2; }
注:中文字符长度1,英文字符及数字长度0.5
posted on 2015-08-29 17:16 bibibi_liuliu 阅读(2627) 评论(0) 编辑 收藏 举报