UILabel切断自定义字体。 如何根据select的自定义字体dynamic调整UILabel高度?

在UILabel中显示的一些自定义字体已经加载到我的应用程序中。 我有多个自定义字体,我需要正确显示。 我怎样才能解决这个问题?

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

经过多次search,我发现一个解决scheme ,需要你下载一个程序,调整字体的上升和下降使用terminal,然后在你的应用程序进行testing,直到它是完美的。

如果我不必为20多种字体做这个,那就没问题了。 所以我决定挖掘一下,看看是否可以访问字体的上行和下行值。 结果UIFont具有这些确切的属性!

有了这些信息,我就可以inheritanceUILabel的属性,并通过向其高度添加上行和下行值(使用绝对值,因为它是负值)来dynamic调整其框架。

下面是下面的代码片段,最后一行是钱线:

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))]; 

尝试覆盖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) } }