Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set UITextView's height dynamically in UITableViewCell based on string size?

I understand that this question has been asked here, but it didn't solve my problem as the link in the accepted answer is down and the minimal example didn't help.

Here is a picture of my custom UITableViewCell & all its constraints:

enter image description here

Each post contains these UI elements. The only element that could make each cell's height different is messageView, because its height depends on the string being displayed. Question is, how do I dynamically set each cell's height? Here's what I have now (Does NOT work, messageView is not shown at all):

func cellForRowAt(indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(...) as! PostCell

    let message = ...
    cell.messageView.text = message

    return cell
}

func heightForRowAt(indexPath: IndexPath) -> CGFloat {
    var cellMinimumHeight: CGFloat = 120
    if let cell = tableView.cellForRow(at: indexPath) as? PostCell {
        let size = cell.messageView.sizeThatFits(cell.messageView.frame.size)
        cellMinimumHeight += size.height
    }

    return cellMinimumHeight
}

in heightForRowAt function, the if is not being executed, therefore, all cells' heights are cellMinimumHeight = 120.

How could I make each cell's height = 120 + messageView's height?

---------------------------------EDIT 1---------------------------------

Made a mistake in the picture, messageView's height is not set

like image 603
K.Wu Avatar asked May 22 '18 03:05

K.Wu


3 Answers

When using Auto-Layout for dynamically sizing cells, you don't really need to implement sizeThatFits(...). If the constraints are setup correctly, then you only need to disable the scrolling of the UITextView.

From code:

yourTextView.scrollEnabled = false

From IB:

Select your Text View and open Attributes inspector, then

enter image description here

like image 110
nayem Avatar answered Nov 13 '22 06:11

nayem


In Attributes Inspector select your UITextView(messageView) and Uncheck "Scrolling Enabled".

And then change your UITextView(messageView)'s content compression resistence priority as follows: Horizontal = 750 Vertical = 1000

I hope this will help you.

like image 37
Dhaval Dobariya Avatar answered Nov 13 '22 08:11

Dhaval Dobariya


Just disable UITextview scroll... But here is no use of UITextview, you can use label also.

In HeightForRow tableview delegate method remove that stuff and use

return UITableViewAutomaticDimension
like image 26
Manish Mahajan Avatar answered Nov 13 '22 08:11

Manish Mahajan