美文网首页
iOS 动态设置和获取 UILabel 文字大小

iOS 动态设置和获取 UILabel 文字大小

作者: gaookey | 来源:发表于2020-09-15 23:12 被阅读0次
    let textLable = UILabel(frame: view.bounds)
    textLable.text = "abcd"
    textLable.font = .systemFont(ofSize: 500)
    textLable.textAlignment = .center
    textLable.numberOfLines = 0
    view.addSubview(textLable)
    

    动态设置字体大小

    textLable.adjustsFontSizeToFitWidth = true
    textLable.minimumScaleFactor = 0.02
    

    获取字体大小

    func adjustedFontSize(label: UILabel) -> CGFloat {
        let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)
        text.setAttributes([NSAttributedString.Key.font: label.font as Any], range: NSMakeRange(0, text.length))
        let context: NSStringDrawingContext = NSStringDrawingContext()
        context.minimumScaleFactor = label.minimumScaleFactor
        text.boundingRect(with: label.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: context)
        let adjustedFontSize: CGFloat = label.font.pointSize * context.actualScaleFactor
        return adjustedFontSize
    }
    

    相关文章

      网友评论

          本文标题:iOS 动态设置和获取 UILabel 文字大小

          本文链接:https://www.haomeiwen.com/subject/lsbqyktx.html