【问题标题】:Calculate size of UILabel with different font types计算不同字体类型的 UILabel 的大小
【发布时间】:2014-12-12 12:22:07
【问题描述】:

我正在使用最低版本的 iOS 7 构建应用程序。在我绘制单元格的方法中,我有此代码来绘制具有不同 UIFonts 类型的 UILabel

//Get Strings
NSString* author = [self getUserCreatedVideo:notf];
NSString* caption = [NSString stringWithFormat:@"\"%@\"", [notf objectForKey:@"title"]];
NSString* challenge = @"challenged you to reply to";
NSString* timeToReply = @"24h to reply";
NSString* myString = [NSString stringWithFormat:@"%@ %@ %@ %@", author, challenge, caption, timeToReply];

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:myString];
UIColor* greenColor = [UIColor colorWithRed:102.0/255.0 green:204.0/255.0 blue:153.0/255.0 alpha:1];

//Author
[str addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0,author.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:17.0] range:NSMakeRange(0,author.length)];
//Challenge
[str addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(author.length+1,challenge.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:13.0] range:NSMakeRange(author.length+1,challenge.length)];
//Caption
[str addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(author.length+1+challenge.length+1,caption.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:14.0] range:NSMakeRange(author.length+1+challenge.length+1,caption.length)];
//Time To Reply
[str addAttribute:NSForegroundColorAttributeName value:greenColor range:NSMakeRange(author.length+1+challenge.length+1+caption.length+1,timeToReply.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:14.0] range:NSMakeRange(author.length+1+challenge.length+1+caption.length+1,4)];

cell.subtext.attributedText = str;

现在我想计算UILabel 的文本大小,这样我就可以在cell.subtext 下方画一个UILabel 20px。我怎样才能做到这一点?

【问题讨论】:

    标签: ios uilabel uifont cgrect cgsize


    【解决方案1】:

    所以基本上你想在知道文本宽度的情况下计算文本的高度。

    CGRect rect = [str boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    

    按照你想要的方式使用生成的 rect.size。

    【讨论】:

    • 是的,这就是我想要的。我缺乏知识让我问这个。
    猜你喜欢
    • 1970-01-01
    • 2015-07-15
    • 2020-09-02
    • 2013-02-22
    • 2017-05-31
    • 2014-12-30
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多