Samuscarella
Samuscarella

Reputation: 63

UITableViewAutomaticDimension NOT adjusting to UILabel text height

I have a messaging app and have set the labels constraints to 8 on each side of the bubble view. I have not set a height constraint and am trying to figure out why the label is randomly showing MORE height and the wrong size on some cells when scrolling:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 30

The labels are set to number of lines 0 and also word wrap.

    func configureCell(message: MessageCD) {

    self.message = message

    let username = message.getSender()?.username
    let text = message.text

    if username == UserDefaults.standard.value(forKey: USERNAME) as? String {

        senderLbl.text = text
        recipientBubbleView.isHidden = true
        senderBubbleView.isHidden = false
    } else {
        recipientLbl.text = text
        senderBubbleView.isHidden = true
        recipientBubbleView.isHidden = false
    }
}

I also tried using sizeToFit() right after the label is set but this also does not work. See attached image.enter image description here

Upvotes: 1

Views: 284

Answers (1)

Samuscarella
Samuscarella

Reputation: 63

Content Hugging Priority Fixed the issue.

if msgUsername == UserDefaults.standard.value(forKey: USERNAME) as? String {

        recipientLbl.setContentHuggingPriority(250, for: UILayoutConstraintAxis.vertical)
        senderLbl.setContentHuggingPriority(750, for: UILayoutConstraintAxis.vertical)
        senderLbl.text = message.text
        senderLbl.sizeToFit()
        recipientUsernameLbl.isHidden = true
        recipientBubbleView.isHidden = true
        senderBubbleView.isHidden = false

    } else {

        senderLbl.setContentHuggingPriority(250, for: UILayoutConstraintAxis.vertical)
        recipientLbl.setContentHuggingPriority(750, for: UILayoutConstraintAxis.vertical)
        recipientLbl.text = message.text
        recipientUsernameLbl.text = msgUsername
        recipientUsernameLbl.isHidden = false
        recipientLbl.sizeToFit()
        senderBubbleView.isHidden = true
        recipientBubbleView.isHidden = false
    }

Upvotes: 1

Related Questions