Apple并没有给出两边对齐模式的设置,需要自己写两个方法:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 380, 160, 21)];
label2.backgroundColor = [UIColor greenColor];
[self conversionCharacterInterval:7 current:@"今天天气" withLabel:label2];
[self.view addSubview:label2];
}
/**
* 设置UILable里的文字两边对齐
* maxInteger : 应占字符数 (中文为1,英文为0.5/个)
* currentString : 要显示的文字
*/
- (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;
}