UILabel切断了自定义字体。如何根据所选的自定义字体动态调整UILabel高度?

时间:2015-04-15 01:44:54

标签: ios objective-c fonts uilabel font-size

我加载到应用程序中的一些自定义字体在UILabel中显示时会被切断。我有多个自定义字体,我需要正确显示。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:18)

如上所述,我有一个非常恼人的问题,即UILabel中的自定义字体会因某事而被切断。我后来发现这是由于ascenders and descenders(字体特征)。

经过大量搜索,我发现solution要求您下载程序,使用终端调整字体的上升和下降,然后在您的应用上测试它,直到它完美无缺。

如果我没有为20多种字体做这件事,那就没关系了。所以我决定四处搜索,看看我是否可以访问字体的ascender和descender值。原来UIFont有那些确切的属性!

通过这些信息,我能够继承UILabel并通过将ascender和descender值(使用绝对值,因为它为负)添加到其高度来动态调整其框架。

以下是实施代码的片段,最后一行是资金行:

UIFont *font = [UIFont fontWithName:nameOfFontUsed size:44.0];
NSDictionary *attrsDict = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSMutableAttributedString *theString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", enteredString] attributes:attrsDict];

//Add other attributes you desire

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.lineHeightMultiple = 5.0;
[theString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [theString length])];

[self setAttributedText:theString];

[self sizeToFit];

[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height+font.ascender+ABS(font.descender))];

答案 1 :(得分:5)

尝试在UILabel中覆盖intrinsicContentSize属性。

我不认为这是最好的做法,但在某些情况下很容易解决问题。

Swift 3的示例

class ExpandedLabel: UILabel {

  override var intrinsicContentSize: CGSize {

    let size = super.intrinsicContentSize

    // you can change 'addedHeight' into any value you want.
    let addedHeight = font.pointSize * 0.3

    return CGSize(width: size.width, height: size.height + addedHeight)
  }
}