0

I have a table and the cells have a label and I want to be able to update a label directly without reloading the table or cell. I found a way to do this and it works:

let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as! cellClass
     cell.textLabel.text = newText as? String

The only problem is that the size of the label doesn't change. If you reload the table, the label changes size to adapt to the amount of text. I tried using layoutIfNeeded() and sizeToFit() but the label won't extend to a second row. The width isn't a big deal, it's mostly that it doesn't wrap, so in other words the height won't extend for more lines.

Wayne Filkins
  • 494
  • 6
  • 20
  • Also like at my answer http://stackoverflow.com/questions/40293336/uitableviewautomaticdimension-not-working-for-resizing-cell-height/40300589#40300589 – Joe Nov 05 '16 at 00:37
  • Have you tried `tableView.beginUpdates()` followed by `tableView.endUpdates()`? – crizzis Nov 05 '16 at 00:54
  • there's something to the beginUpdates/endUpdates thing. It is doing what I want, but the problem is that sometimes this label gets updated quickly and it seems to be crashing when that happens. For an update or two, it works though. I tried getting main queue but still crashing. Any idea why it's doing this? – Wayne Filkins Nov 05 '16 at 23:29

1 Answers1

0

First off, I would recommend to create a custom cell (a subclass of UITableViewCell), and name that UILabel something different, say articleTitleLabel (depending on your context). "textLabel" is an inherited property, and I guess you could still use that, but make sure you customize it inside "awakeFromNib" method (set numberOfLines = 0, or 2). I would also recommend to add a public instance method inside the custom cell class. Something like this:

function configureWithText(text: String) {
    articleTitleLabel.text = text
    // or, textLabel.text = text
}

Also, you may need to create a .xib file for the custom cell, and set some Top, Bottom, Left and Right constraints to your label.

Hope it helps!

ppalancica
  • 4,236
  • 4
  • 27
  • 42
  • Didn't work. I'm already doing most of these things, and added a function instead of changing the text directly but it does the same thing. – Wayne Filkins Nov 05 '16 at 23:12