ios - 根据内容调整 UILabel 的大小

标签 ios iphone uilabel uifont

我有一个UILabel,他的文字大小有属性

title.adjustsFontSizeToFitWidth = YES;

这会阻止我使用标准方法来调整 UILabel 的大小。我在这里的另一篇文章中读到我应该使用该函数

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode

来自这个答案:How to figure out the font size of a UILabel when -adjustsFontSizeToFitWidth is set to YES?

现在,我想不出如何让它工作..这是实际的代码

UIFont *font = [UIFont fontWithName:@"Marker Felt" size:200];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 20.0)];
title.text = @"this is a long title that should be resized";
title.font = font;
title.numberOfLines = 1;
title.adjustsFontSizeToFitWidth = YES;

CGFloat pointSize = 0.0;
CGSize size = [title.text sizeWithFont:font 
                           minFontSize:title.minimumFontSize 
                        actualFontSize:&pointSize 
                              forWidth:width 
                         lineBreakMode:title.lineBreakMode];
title.frame = CGRectMake(title.frame.origin.x, 
                         title.frame.origin.y, 
                         size.width, 
                         size.height);

UILabel 的大小调整错误,就好像字体大小仍然是 200.. 有什么线索吗?谢谢!

最佳答案

我的 github 上有一些你可以使用的代码,检查一下,它是 UILabel 的一个类别,你需要设置框架宽度,当你可以在 UILabel 上调整尺寸时,它会调整高度以适合内容,并且返回标签末尾的 y 位置,以便您可以调整出现在它后面的任何内容。

https://gist.github.com/1005520

关于ios - 根据内容调整 UILabel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242608/

相关文章:

iphone - iOS - 从 MFMailComposeViewController 中删除 UIImageView

ios - 着色器程序在 Cocos2d 2.2 Obj.C iOS 12 中无法运行

ios - 删除字典中的特定重复项

ios - 无法在 iTunes connect 中请求新契约(Contract)(适用于 iOS 付费应用程序)

ios - 离开 View Controller 时,UISwitch 不会保持其值

iphone - 如何将 Corona 与现有 Xcode 项目集成

ios - 使用 swift 更新到 Xcode 6.2 后,cell.textLabel.text 不工作

ios - 给定带有多行标签的 Collection View 单元格的宽度,如何获得首选的 AutoLayout 高度?

objective-c - 使 UIScrollview 滚动

ios - JSON POST Web 服务中的多个 Json 对象和 3 个字符串