您的位置:首页 > 产品设计 > UI/UE

IOS-55-UILable文字两边对齐的实现方式

2016-03-01 12:38 656 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: