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?

Navio53
  • 591
  • 1
  • 6
  • 20
  • Check this other question to see if helps http://stackoverflow.com/questions/8796862/uilabel-auto-size-label-to-fit-text – Claudio Redi May 16 '15 at 02:35

4 Answers4

8

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

Yu's Way
  • 142
  • 3
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
}
HangarRash
  • 7,314
  • 5
  • 5
  • 32
Joseph Selvaraj
  • 2,225
  • 1
  • 21
  • 21
  • Never gets called for me? – William T. Mallard Jan 28 '18 at 19:25
  • 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. – HangarRash May 16 '23 at 18:12
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
        

    }
Erhan Demirci
  • 4,173
  • 4
  • 36
  • 44
-1

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

cell.textLabel?.numberOfLines=0
R3n4
  • 49
  • 1
  • 2