Get UILabel Size After Text Programming

When setting some string value to a UILabel text attribute like

var a : UILabel
a.text = "Variable length string"

autolayout resizes using constraint font size, number of line labels, etc.

Question: if I needed to get the size of this label so that I could (for example) decide how tall the table cell that includes this label should be, at what point is this successful?

Trying to figure this out without using the UITableviewAutomaticDimension.

EDIT . The answer, posted as a possible duplicate, has some similarities. However, my main confusion is where I can successfully and confidently extract the heights of UILabel.

It has been many times that I tried to get the size of the view, but the value I return is inaccurate and you need to resort to using viewDidLayoutSubviews () in one form or another. I guess I don’t understand what order of things happens in the layout very well. And this seems different for viewDidLoad () and awakeFromNib () too, but I could be wrong about that.

If someone can point me in the right direction in understanding this, I would be grateful

+4
source share
1 answer

Try implementing the following method in your ViewController using tableView:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
             return HeightCalculator.height(with: text, inViewController: self)
}

Then add the following class:

import UIKit

class HeightCalculator {
    let title: String
    let viewController: UIViewController

    class func height(with title: String, inViewController viewController: UIViewController) -> CGFloat {
        let calculator = HeightCalculator(title: title, viewController: viewController)

        return calculator.height
    }

    init(title: String, viewController: UIViewController) {
        self.title = title
        self.viewController = viewController
    }

    var height: CGFloat {
        let contentHeight = title.heightWithConstrainedWidth(width: defaultWidth, font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1))
    }
}

:

import UIKit

extension String {
    func heightWithConstrainedWidth(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 boundingBox.height
    }
}

heightForRowAt , , (contentHeight) . , , heightWithConstrainedWidth.

+2

Source: https://habr.com/ru/post/1673092/


All Articles