如何检查UILabel的当前字体大小?

时间:2018-10-22 12:22:33

标签: ios swift uikit

我有3种UILabels,并且我想为所有这些字体设置相同的字体(这是三种可能性中最小的一种)。问题是什么?我不知道如何检查当前字体-UILabels中的每一个都使用Autoshrink,并且最小的字体比例和行数等于0。UILabels的文本是在ViewDidLoad()方法中设置的(标签文本有很多组合。)

我尝试使用UILabel.font.pointSize属性(在viewDidAppear()方法中调用)获取当前字体大小,然后比较所有字体。问题在于,UILabel.font.pointSize返回的不是UILabel文本字体大小的当前值(完成Autoshrink之后),而是返回在情节提要中设置的值。

我完全没有主意,谢谢您的帮助!

问候,约翰

3 个答案:

答案 0 :(得分:0)

我发现在viewDidLoad()内部您的约束尚未完全定义。您可以尝试使用其他方法进行这些计算,例如viewWillAppear()或任何适合您并在viewDidLoad()之后执行的方法。

答案 1 :(得分:0)

这是获取UILabel当前大小的一种方法,尽管我知道有更多方法可以解决此问题。这是最干净最快的。请参见示例和扩展。

import UIKit

class ViewController: UIViewController {

    lazy var label1 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: 80, width: self.view.bounds.width - 40, height: 40))
        lbl.text = "This is some large text to make it fit to size with a big font size"
        lbl.font = UIFont.systemFont(ofSize: 50, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()

    lazy var label2 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: label1.frame.maxY + 5, width: self.view.bounds.width - 40, height: 40))
        lbl.text = "This is one line"
        lbl.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()

    lazy var label3 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: label2.frame.maxY + 10, width: self.view.bounds.width - 40, height: 80))
        lbl.text = "This is some large text to make it fit to size with a big font size"
        lbl.font = UIFont.systemFont(ofSize: 100, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.addSubview(label1)
        self.view.addSubview(label2)
        self.view.addSubview(label3)

        var minSize : CGFloat = .greatestFiniteMagnitude
        for sub in self.view.subviews{
            if let lbl = sub as? UILabel{
                //get the size
                let font = lbl.adjustedFont()
                print("the size is \(font.pointSize)")
                minSize = min(font.pointSize,minSize)
            }
        }
        print("the minimum for all fonts is \(minSize)")
        print("i am going to delay for 3 seconds and then reset all the labels to the minimum size :)")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.0) {
            for sub in self.view.subviews{
                if let lbl = sub as? UILabel{
                    lbl.font = lbl.font.withSize(minSize)
                }
            }
        }
    }
}
extension UILabel{
    func adjustedFont()->UIFont {
        guard let txt = text else {
            return self.font
        }
        let attributes: [NSAttributedString.Key: Any] = [.font: self.font]
        let attributedString = NSAttributedString(string: txt, attributes: attributes)
        let drawingContext = NSStringDrawingContext()
        drawingContext.minimumScaleFactor = self.minimumScaleFactor
        attributedString.boundingRect(with: bounds.size,
                                      options: [.usesLineFragmentOrigin,.usesFontLeading],
                                      context: drawingContext)

        let fontSize = font.pointSize * drawingContext.actualScaleFactor
        return font.withSize(CGFloat(floor(Double(fontSize))))
    }
}

实际示例

enter image description here

答案 2 :(得分:0)

使用此扩展

extension String {

       func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

            return ceil(boundingBox.height)
        }
}

获取身高

height = strDesc.height(withConstrainedWidth: UIScreen.main.bounds.size.width - 160, font: UIFont.systemFont(ofSize: 14.0))