0

I'm making a simple texting app for practice and the UITableView has lots of cells containing messages.

Texting App

It works well with one-line messages but, as you can see on the bottom, with multi-line texts the size of the UITableViewCell starts getting in the way and cutting the message short. Just in case, here's the code for my cellForRowAtIndexPath method:

internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = UITableViewCell()
    if usernames[indexPath.row] == PFUser.currentUser()?.username {
        cell = tableView.dequeueReusableCellWithIdentifier("text")!
    } else {
        cell = tableView.dequeueReusableCellWithIdentifier("reply")!
        (cell.viewWithTag(2) as! UILabel).text = usernames[indexPath.row]
    }
    (cell.viewWithTag(1) as! UILabel).text = messages[indexPath.row]

    return cell
}

Basically I just need a solution that will enable this app to support multi-line messages. Thanks in advance for any help!

James
  • 53
  • 7

3 Answers3

2

Two things you need to do:

1) In viewDidLoad, specify these:

tableView.rowHeight = UITableViewAutomaticDimension
# The estimated row height number is not that important, just approximate it
tableView.estimatedRowHeight = 140

2) Define all constraints for your custom cell. Make sure top and bottom constraints specifically are defined.

The second step is particularly important.

leonardloo
  • 1,753
  • 3
  • 20
  • 31
1

1) On Storyboard, In Attribute Inspector section. Set Lines = 0

2) In func viewDidLoad(),

    tableView.estimatedRowHeight = 50.0
    tableView.rowHeight = UITableViewAutomaticDimension
Pranit
  • 892
  • 12
  • 20
0

You can use self-sizing table view cells and UITableViewAutomaticDimension. This is quite good article about it.

The trick to getting Auto Layout to work on a UITableViewCell is to ensure you have constraints to pin each subview on all sides — that is, each subview should have leading, top, trailing and bottom constraints. Then, the intrinsic height of the subviews will be used to dictate the height of each cell. You’ll do this now.

Then setup rowHeight to UITableViewAutomaticDimension:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
Asya
  • 279
  • 2
  • 7