iOS UILabel 中的文本设置固定宽度

- (void) labelAlightLeftAndRightWithWidth:(CGFloat) labelWidth {

    CGSize testSize = [self.text boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine| NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :self.font} context:nil].size;

    

    CGFloat margin = (labelWidth - testSize.width)/(self.text.length - 1);

    NSNumber *number = [NSNumber numberWithFloat:margin];

    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:self.text];

    

    [attribute addAttribute: NSKernAttributeName value:number range:NSMakeRange(0, self.text.length - 1 )];

    self.attributedText = attribute;

}

猜你喜欢

转载自blog.csdn.net/yxl123546/article/details/76664142