Wrap Text in UITableView Custom Cell When It Reaches End of Screen (Swift)
Asked Answered
E

4

7

I have a table that loads data from a database but the problem is if the text being loaded is too long, it goes off the screen. I'm trying to find a way for the text to go onto the next line and have the cell resize automatically to fit this change. Does anyone know how this is done? The cell has three labels but one of them is allowed to be multi-lined.

EDIT:

I got it to work using auto constraints but how can I resize the table cell so that the actual items fit inside the cell and do not go over the cell boundary?

Enshrine answered 16/5, 2015 at 2:27 Comment(1)
Check this other question to see if helps #8797362Beefburger
H
8

Set label number of "Lines" to ZERO. And set "Line Breaks" to "Word Wrap"

Holsworth answered 16/5, 2015 at 3:10 Comment(1)
At first it didn't work, then I had set the Lines to 0 in the storyboard as well.Heedful
P
7

Adding these two methods along with above code fixed the problem with custom font

tamilRow.textLabel?.numberOfLines=0
tamilRow.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Phidippides answered 23/3, 2016 at 7:30 Comment(2)
Never gets called for me?Sepal
In a case like this, it's better to set self.tableView.rowHeight and self.tableView.estimatedRowHeight once in viewDidLoad and not implement the two delegate methods. Only implement the delegate methods if different rows need to return a different value.Ale
A
0

swift 5

let unselectedCellHeight: CGFloat = 130.0

func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if selectedCellIndexPath == indexPath {
            //return selectedCellHeight
            return UITableView.automaticDimension
        }
       return unselectedCellHeight
        

    }
Aesculapius answered 29/1, 2023 at 13:36 Comment(0)
G
-1

I only had to set the number of lines to 0 in order to wrap the text:

cell.textLabel?.numberOfLines=0
Gobelin answered 16/5, 2023 at 17:21 Comment(1)
This is what the accepted answer states.Ale

© 2022 - 2024 — McMap. All rights reserved.