4

I have a custom UITableViewCell with a UILabel that has multiple lines. I'm trying to implement a tap expand/contract feature so that when the label is only one line, no expansion happens when you tap the cell, but if the label is multiple lines, the cell is capable on expanding/contracting when tapped. I got the expansion and contracting working, but I can't figure out how to make it work based on the number of lines in the UILabel.

This is currently what I'm doing for the cell expansion, but its not based on the UILabel at all.

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

    if (indexPath.row == self.selectedRow?.row && self.expand == true)
    {
        self.previousRow = self.selectedRow?.row
        return 200 
    }
    else if(self.previousRow == self.selectedRow?.row && self.expand == false){
        return 65
    }      
    return 65
}  
casillas
  • 16,351
  • 19
  • 115
  • 215
Brosef
  • 2,945
  • 6
  • 34
  • 69
  • Since you have custom cell item, then add tap gesture recognition to your label, then when user tap on the item, it will check the condition, if condition matches ,then either expands or contracts. – casillas Dec 14 '15 at 17:55
  • You could also check how many lines in the label, check this thread http://stackoverflow.com/questions/4172615/how-to-find-uilabels-number-of-lines – casillas Dec 14 '15 at 17:57
  • @casillas I like the gesture recognition option, but it might not be intuitive enough. I'm not using `didSelecRowAtIndexPath` for anything, so I might as well use it for this. I looked through the link you provided, but since this is a tableviewcell, where should I access the cells label size? Doesn't make sense to do it in cellForRowAtIndexPath, right? – Brosef Dec 14 '15 at 18:07

2 Answers2

7

You can use table view dynamic cell sizing with autolayout in conjunction with the numberOfLines property of UILabel to expand and compress cell.

The heart of the solution is this:

tableView.beginUpdates()
label.numberOfLines = label.numberOfLines == 0 ? 1 : 0
tableView.endUpdates()

This is essentially triggering an animation on the table and toggling the number of lines from 0 (any number of lines) to 1 line. Autolayout is doing the rest.

I think this is better than updating height metrics manually. The full example project can be found on my github: https://github.com/rayfix/MultilineDemo

demonstration

Ray Fix
  • 5,575
  • 3
  • 28
  • 30
0

You probably need to measure the text yourself because the label won't have more lines until you expand.

Something like this (the 100000 just needs to be a big number)

CGSize textSize = [self.label.text sizeWithFont:self.label.font constrainedToSize:CGSizeMake(self.label.bounds.width, 100000) lineBreakMode: UILineBreakModeWordWrap]; 
Lou Franco
  • 87,846
  • 14
  • 132
  • 192