ios - 标签高度错误

标签 ios objective-c xcode ios8

我正在尝试根据文本的长度获取标签的高度。但如果单词不能放在一行中 - 部分单词将转移到下一行。并且该方法仅返回一行的高度。谁能帮我吗?

- (CGFloat)heightFromText:(NSString *)text{
if (!text) {
    return 0.0;
}
UIFont *font = [UIFont systemFontOfSize:16.0];
UIColor *color = [UIColor colorWithColorCode:@"438fbe"];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle alloc];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary *attributes = @{NSForegroundColorAttributeName : color, NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle};
NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:text attributes:attributes];
CGRect needed = [attributed boundingRectWithSize:CGSizeMake(self.width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
CGFloat textHeight = ceilf(needed.size.height);
return textHeight;

最佳答案

试试 UILabel,像这样:

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(x,y,w,h)];
lbl.font=font; 
lbl.numberOfLines=0; // will do as many lines as you need
lbl.textAlignment=NSTextAlignmentLeft;
lbl.attributedText=attString;

CGSize size = [lbl.text sizeWithFont:lbl.font
                       constrainedToSize:CGSizeMake(lbl.frame.size.width, MAXFLOAT)
                           lineBreakMode:NSLineBreakByWordWrapping];
return size.height;

关于ios - 标签高度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28064915/

相关文章:

ios - 如何在 build.sh 中正确设置编译器以在 iOS 中构建 VLC

objective-c - 重写setter方法并获取“xxx的本地声明隐藏实例变量”

iphone - 如何使用 UIsearchBar 委托(delegate)方法关闭键盘?我尝试了所有方法,但没有用。

iOS:特定 View Controller 类的 didReceiveRemoteNotification

c++ - 如何让 C 方法接受 UIImage 参数?

objective-c - 使用 performSelectorInBackground 时收到内存警告

swift - 没有这样的模块

ios - Xcode 选项卡式应用程序 - 添加新选项卡 View

ios - 新 iPhone 6 和 6+ 的 iAds

iphone - 在可重用表格单元格中使用 NSCache 和 dispatch_async 的正确方法是什么?