【问题标题】:UILabel cuts off custom font. How do I dynamically adjust UILabel height based on custom font selected?UILabel 切断自定义字体。如何根据选择的自定义字体动态调整 UILabel 高度?
【发布时间】:2015-06-20 19:44:18
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    如前所述,我遇到了一个非常烦人的问题,UILabel 中的自定义字体会由于某些原因 而被截断。后来发现是ascenders and descenders(字体特征)造成的。

    经过大量搜索,我找到了一个solution,要求您下载程序,使用终端调整字体的升序和降序,然后在您的应用上进行测试,直到完美为止。

    如果我不必为 20 多种字体执行此操作,那就没问题了。所以我决定四处挖掘,看看我是否可以访问字体的上升和下降值。原来 UIFont 具有这些确切的属性!

    有了这些信息,我能够继承 UILabel 并通过将上升和下降值(使用绝对值,因为它是负数)添加到它的高度来动态调整它的框架。

    下面是一个sn-p的实现代码,最后一行是钱行:

    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 的子类。上面的代码你覆盖了什么方法?
    【解决方案2】:

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

    【讨论】:

    • 作为添加font.pointSize 的一部分的替代方法,我添加了font.ascender
    • 此解决方案仅适用于 UILabel 的自动布局
    • 正是我需要避免在带有“È”作为特殊字符的标签中被截断,即在 TableView 中的 StackView 中。我用过return CGSize(width: size.width, height: size.height + font.ascender)
    猜你喜欢
    • 2011-11-18
    • 2011-06-05
    • 1970-01-01
    • 2013-06-10
    • 2012-04-02
    • 1970-01-01
    • 2014-01-05
    • 2011-04-09
    • 2013-06-05
    相关资源
    最近更新 更多