iphone - adjustmentFontSizeToFitWidth 无法正常工作

标签 iphone ios5 ios6 uilabel

我正在开发一个适用于 iOS > 5.0 并使用 Xcode 4.6.2 的应用程序 为了解释我的问题,我有一个 UIScrollView ,它只包含一堆 UILabel 。我要在这些 UILabel 中显示的文本是动态的,但是 UILabel 的框架是恒定的,因此如果当前文本不适合框架宽度,我需要缩小字体大小。所以,我找到了 UILabeladjustsFontSizeToFitWidth 属性。

这是我直接从 UILabel 类引用中获取的解释。

A Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle.

是的,我认为这就是我正在寻找的内容,因为我要在 UILabel 中显示的文本始终是一行。 所以我知道这个属性应该与 numberOfLines 属性一起使用来设置 1。

这是我实现此目的的代码。

for (NSString *currentImage in self.imagesNames)
{
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(imageNumber*resultTypeImageWidth, 10, 75, 35)];
    [lbl setFont:[UIFont fontWithName:@"GothamRounded-Bold" size:25]];
    [lbl setNumberOfLines:1];
    [lbl setText:currentImage];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setTextColor:[UIColor colorWithHue:0.07 saturation:1 brightness:0.49 alpha:1.0]];
    [lbl adjustsFontSizeToFitWidth];
    [lbl setTextAlignment:NSTextAlignmentCenter];
    imageNumber++;
    [self.resultTypeScrollView addSubview:lbl];
}

imageNumber 是一个 int,我用它来将此 UILabel 放置在我的 UIScrollView 中的适当位置> 这是名称 resultTypeScrollViewresultTypeImageWidth 是我定义的一个常量,并设置为 100 以在 UILabel 之间留出一些空间。

所以,我的问题是,如果文本不适合标签的框架,它就会被截断。我预计如果文本不适合框架,字体大小将缩小以适应框架。至少,这是我从 UILabel class reference 中了解到的。显然,我错过了一些东西,但是什么呢?

到目前为止,

  1. 由于我使用的是自定义字体,我怀疑使用自定义字体会出现问题。所以,我换了一种系统字体,没有效果。
  2. 我尝试将 NSLineBreakMode 设置为 NSLineBreakByClipping 以防止文本被截断。之后,文本不会被截断,但会丢失一些之前被截断的字符。
  3. 我还使用了 minimumScaleFactor 设置不同的值来查看是否有任何效果,但是根本没有效果。

最佳答案

这应该可以在不更改许多默认值的情况下工作。发布的代码没有设置adjustsFontSizeToFitWidth,它只是获取它。设置如下所示:

lbl.adjustsFontSizeToFitWidth = YES;

关于iphone - adjustmentFontSizeToFitWidth 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17776061/

相关文章:

iphone - Objective-C JSON - 将 JSON 对象转换为 native 对象?

ios - 无法创建 lldb private : Xcode can't run the app on iphone

iphone - 如何从iPhone应用程序链接到iTunes store应用程序中的“特色音乐”部分?

iphone - 如何更改UIButton点击(触摸)事件的文本标签?

iphone - iOS TableView 加载数据很慢

ios - 在 iOS6 中获取用户个人资料图片?

ios - 方法不是在 iPhone 中调用而是在 iOS 模拟器中调用

objective-c - 如何从 NSArray 获取元素

iphone - dequeueReusableCellWithIdentifier 不返回我的自定义类型的单元格

iphone - iOS6 中设备旋转时选项卡栏应用程序崩溃