计算文字的宽度(动态)

来源:互联网 发布:淘宝生发液骗局 编辑:程序博客网 时间:2024/05/16 06:08
//交易订单数字    UILabel*TONumberLab = [[UILabel alloc] init];    TONumberLab = [self createTitleAndNumberLab:@"567" fontSize:TONumberFontSize];    CGSize TONumberLabSize = [self sizeWithText:TONumberLab.text font:TONumberLab.font fontSize:TONumberFontSize];


#pragma mark 计算文字尺寸/** *  计算文字尺寸 * *  @param text    需要计算尺寸的文字 *  @param font    文字的字体 *  @param maxSize 文字的最大尺寸 */- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font fontSize:(CGFloat)fontSize{    CGSize maxSize = CGSizeMake(MAXFLOAT, fontSize);    NSDictionary *attrs = @{NSFontAttributeName : font};    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;}

#pragma mark 创建标题Lab/** *  创建标题/数字Lab * *  @param title    标题/数字 *  @param fontSize 标题/数字字号大小 * */-(UILabel*)createTitleAndNumberLab:(NSString*)title fontSize:(CGFloat)fontSize{    //本月收款(元)    UILabel*tmpLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];    tmpLab.font = [UIFont systemFontOfSize:fontSize];    [tmpLab setTextColor:[UIColor whiteColor]];    [tmpLab setText:title];    return tmpLab;}

不封装计算宽度   //最新订单    UILabel *latestOrderLab = [[UILabel alloc]init];    [latestOrderLab setText:@"最新订单"];    [latestOrderLab setFont:[UIFont systemFontOfSize:LatestOrderAndRefreshLabFontSize]];    [latestOrderLab setTextColor:UIColorFromRGB(0x333333)];    NSDictionary *attrs = @{NSFontAttributeName : latestOrderLab.font};    CGSize maxSize = CGSizeMake(MAXFLOAT, LatestOrderAndRefreshLabFontSize);    CGSize latestOrderLabSize = [latestOrderLab.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;    CGFloat latestOrderLabX =SpaceLabHeight;    CGFloat latestOrderLabY =SpaceLabHeight;    CGFloat latestOrderLabW =latestOrderLabSize.width;    CGFloat latestOrderLabH =latestOrderLabSize.height;    latestOrderLab.frame = CGRectMake(latestOrderLabX, latestOrderLabY, latestOrderLabW, latestOrderLabH);    [latestOrderAndRefreshView addSubview:latestOrderLab];



0 0