iosswiftuitableviewheightforrowatindexpathuitableviewautomaticdimension

How to CORRECTLY increase UITableViewCell using UILabel's height


There have been so many answers to this question on stack overflow, please know that I have looked but all the solutions do not work for me. I have two UILabels in the cell, one has a definite width and height, the other which will be dynamic, I put the width about <= 250 and the height >=50. I have also set all four margins to the content view and then I tried these two methods below to get the height of the string:

var context: NSStringDrawingContext = NSStringDrawingContext()
        context.minimumScaleFactor = 0.8
        cell?.body.text = msg.body
        var width: CGFloat = (cell?.body.frame.size.width)!
        width = ((UIScreen.main.bounds.width)/320)*width
        let size: CGSize = (cell?.body.text!.boundingRect(with: CGSize(width: width, height: 2000), options:NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: cell?.body.font], context: context).size)!
        print("size.height is \(size.height)")
        return size.height

and this method:

var optimalHeight : CGFloat
{
    get
    {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: CGFloat.greatestFiniteMagnitude))
        //let label = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = self.lineBreakMode
        label.font = self.font
        label.text = self.text

        label.sizeToFit()

        return label.frame.height
    }
}

and for these two, the image attached is what shows as the UILabel, which, as anyone can see, is way off.enter image description here

I have also tried implementing UITableViewAutomaticDimension in the estimatedHeightForRowAt and heightForRowAt methods, but this did not work, after two lines, it would not expand further. I tried calling estimatedRowHeight and rowHeight in the viewDidLoad() method like this:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300 //even went as far as using 800

same thing, stopped expanding after 2 lines. I also saw something about implementing these methods:

tableView.setNeedsLayout()
tableView.layoutIfNeeded()

and yet nothing! I have looked through the raywenderlich tutorial and a lot more. I have no clue what I am doing wrong. This might be a duplicate question but I assure you I have tried every solution and nothing works for me. Please could someone take a look at this and see what I am doing wrong?

these are the screenshots of the constraints for both labels enter image description hereenter image description here


Solution

  • So I wrapped my dequeuing in cellForRowAt on a background thread and this prevented my cells from being dynamic. After I took that statement out, it worked perfectly! Such a waste of code time fixing something that was never broken