0

I am very new to Swift and working on my very first Swift app.

I have a tableview with a multiline cell that needs to fit in long text if needed.

My code is:

    cell.textLabel!.text = celltextname
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

As you can see, the multiline works, but the text overflows the cell.

enter image description here

In this case, I need either the cell height to increase dynamically, or have the text size reduce to fit the cell.

How can I do this?

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
R2D2
  • 2,620
  • 4
  • 24
  • 46
  • 1
    see here: https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights?rq=1 – user2378197 Jun 09 '17 at 18:15

1 Answers1

3

If you want your text to fit in the cell you can use this:

cell.textLabel?.adjustsFontSizeToFitWidth = true

If you want to adjust the height of the cell depending on the text height you can use this:

func getTextViewHeight(text: String, font: UIFont) -> CGFloat {
    let textSize: CGSize = text.size(attributes: [NSFontAttributeName: font])
    var height: CGFloat = (textSize.width / UIScreen.main.bounds.width) * font.pointSize

    var lineBreaks: CGFloat = 0
    if text.contains("\n") {
        for char in text.characters {
            if char == "\n" {
                lineBreaks += (font.pointSize + 12)
            }
        }
    }

    height += lineBreaks
    return height + 60
}

So you basically use this inside your heightForRowAt function and calculate each cell height.

Update: To calculate the height:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return getTextViewHeight(text: array[indexPath.row], font: UIFont.systemFont(ofSize: 14))
}

Where array is the datasource you have.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • I think changing the height of the cell is the better solution. How can I call this function from heightForRowAt and pass the text string to this function? – R2D2 Jun 09 '17 at 17:41
  • @Richard, I agree. Check the update for instructions of how to use `getTextViewHeight` – Rashwan L Jun 09 '17 at 17:45