多个大小不同的UILabel底部对齐的方法

来源:互联网 发布:老男孩linux运维2017 编辑:程序博客网 时间:2024/05/20 06:28

原文链接:http://blog.csdn.net/hjaycee/article/details/48393455


在界面设计中,经常有这样的需求,比如一个商品的价格是8888的字体设置的很大,的字体设置的很小,要求底部对齐。

但是即便是使用Autolayout自动得到label的大小,在设置label的背景色后会发现label的上下方都有内边距,这是因为这个内边距本身就包括在字体的尺寸内的。

那么如何得到字体实际显示的大小呢?我在UIFont中找到了两个属性:ascendercapHeight。第一个可以得到中文字体的实际显示大小,第二个可以得到英文字母和数字的实际显示大小。

最后附上例子:


//  HJBottomAlignmentLabel.h#import <UIKit/UIKit.h>@interface HJBottomAlignmentLabel : UIView- (void)addText:(NSString *)text Font:(UIFont *)font TextColor:(UIColor *)textColor IsChinese:(BOOL)isChinese;@end//  HJBottomAlignmentLabel.m#import "HJBottomAlignmentLabel.h"@implementation HJBottomAlignmentLabel- (void)addText:(NSString *)text Font:(UIFont *)font TextColor:(UIColor *)textColor IsChinese:(BOOL)isChinese{    UILabel *label = [UILabel new];    label.text = text;    label.font = font;    label.textColor = textColor;    label.backgroundColor = [UIColor clearColor];    [self addSubview:label];    CGSize size = [text sizeWithFont:font];    CGFloat labelH = isChinese ? font.ascender : font.capHeight + 0;    self.frame = CGRectMake(0, 0, self.bounds.size.width + size.width, MAX(labelH, self.bounds.size.height));    label.frame = CGRectMake(self.bounds.size.width - size.width, self.bounds.size.height - labelH, size.width, labelH);}@end// 调用HJBottomAlignmentLabel *hjLabel = [HJBottomAlignmentLabel new];[hjLabel addText:@"88" Font:[UIFont systemFontOfSize:200] TextColor:[UIColor redColor] IsChinese:NO];[hjLabel addText:@"元" Font:[UIFont systemFontOfSize:40] TextColor:[UIColor blueColor] IsChinese:YES];hjLabel.center = self.view.center;hjLabel.backgroundColor = [UIColor greenColor];[self.view addSubview:hjLabel];


0 0
原创粉丝点击