Dynamic Resizing of UILabel Based on Text Content

31 Views Asked by At

Due to some of the data from the API being in the form of long lines and some being short, there is sometimes a significant gap between two labels. I tried the following method to resolve this issue, but it's not working.

func adjustLabelHeight(label: UILabel) {
    
    label.numberOfLines = 0 
    label.lineBreakMode = .byWordWrapping 
    label.sizeToFit() 
    
    label.setContentHuggingPriority(.required, for: .vertical)
    label.setContentCompressionResistancePriority(.required, for: .vertical)
}

func fetchData() {

   DispatchQueue.main.async {

     self.ingredientLabel.text = foodInfo.ingredients.joined(separator: "\n")
     self.methodLabel.text = foodInfo.method.compactMap({ $0.step1 }).joined(separator: "\n")

     self.adjustLabelHeight(label: self.ingredientLabel)
     self.adjustLabelHeight(label: self.methodLabel)

     self.view.layoutIfNeeded()
                            }
0

There are 0 best solutions below