【问题标题】:How to adjust font size to fit height and width of UILabel如何调整字体大小以适应 UILabel 的高度和宽度
【发布时间】:2016-01-22 17:29:58
【问题描述】:

我有一个正方形 UILabel(黄色),其中包含一个字母。

我使用this SO answer 中的以下代码来调整字体大小,使其适合UILabel

letterLabel.font = UIFont(name: letterLabel.font.fontName, size: 100)
letterLabel.adjustsFontSizeToFitWidth = true
letterLabel.textAlignment = NSTextAlignment.Center

如屏幕截图所示,字体大小取决于宽度。但是由于文本只有一个字母,因此我们还需要查看高度。我们如何调整字体大小,使高度也在UILabel 之内?

【问题讨论】:

  • 尝试使用letterLabel.sizeToFit()
  • 我面临着完全相同的情况。你找到解决方案了吗?如果能用IB做,那就更好了!

标签: ios swift uilabel


【解决方案1】:

我没有找到任何简单的解决方案,所以我做了这个扩展:

extension UILabel {
    func setFontSizeToFill() {
        let frameSize  = self.bounds.size
        guard frameSize.height>0 && frameSize.width>0 && self.text != nil else {return}

        var fontPoints = self.font.pointSize
        var fontSize   = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints)])
        var increment  = CGFloat(0)

        if fontSize.width > frameSize.width || fontSize.height > frameSize.height {
            increment = -1
        } else {
            increment = 1
        }

        while true {
            fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints+increment)])
            if increment < 0 {
                if fontSize.width < frameSize.width && fontSize.height < frameSize.height {
                    fontPoints += increment
                    break
                }
            } else {
                if fontSize.width > frameSize.width || fontSize.height > frameSize.height {
                    break
                }
            }
            fontPoints += increment
        }

        self.font = self.font.withSize(fontPoints)
    }
}

【讨论】:

    【解决方案2】:

    我只需要在标签中显示一个字母(姓名首字母),所以要求很明确,它必须缩放以适应高度。

    解决方案:

    class AnyView : UIView{
         private var nameLabel:UILabel! = nil
    
         override func layoutSubviews() {
            super.layoutSubviews()
            //Considering the nameLabel has been already created and added as subview with all the constraint set
            nameLabel.font = nameLabel.font.withSize(nameLabel.bounds.height * 0.6/*The factor can be adjusted as per need*/)
        }
    }
    

    【讨论】:

      【解决方案3】:

      我已经测试过你的代码对我来说可以正常工作。

      我认为单元格高度是个问题,我没有给出单元格高度。 尝试删除单元格高度

      【讨论】:

        【解决方案4】:

        试试[label sizeToFit][label sizeThatFits:(CGSize)]

        【讨论】:

        • 这会调整标签的大小以适应文本,而不是像所要求的那样相反。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 2017-12-15
        • 2023-03-19
        • 2017-07-24
        相关资源
        最近更新 更多