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

Jus*_*der 14 fonts objective-c font-size uilabel ios

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

Jus*_*der 18

如上所述,我有一个非常烦人的问题,UILabel中的自定义字体会因某些东西而被切断.我后来发现它是由于上升和下降(字体特征).

经过多次搜索,我找到了一个解决方案,要求你下载一个程序,使用终端调整字体的上升和下降,然后在你的应用程序上测试它,直到它完美.

如果我不必为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))];
Run Code Online (Sandbox Code Playgroud)

  • 我理解你将UILabel分类.您覆盖了什么方法并将上述代码放入? (2认同)

Mar*_*ark 5

尝试覆盖UILabel中的internalContentSize属性。

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

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)
  }
}
Run Code Online (Sandbox Code Playgroud)