mday
mday

Reputation: 427

Auto-sizing a uitableviewcell - SWIFT

I am trying to resize a tableviewcell based on the size of a UILabel that can be one or more lines. I need autolayout turned ON for the rest of the app, so I don't want to turn it off to get this working. Target is iOS 7 and iOS 8.

I have tried several solutions, but for some reason I can't seem to get the correct height of the label to automatically adjust or to adjust the cell height.

The problem is occurring in this method: calculateHeightForConfiguredSizingCell. I have put a sample project on Git, so you can see what I am seeing.

https://github.com/mdaymond/cellResizer

This example is based on this article: http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout

Update I checked in an update to the code. It's ALMOST working the way I want and calculating programatically, but for some reason the label height isn't quite sized correctly - it's not getting the full height required. Problem with the original code was that the label needed an explicit width.

Upvotes: 1

Views: 2762

Answers (3)

Alvin George
Alvin George

Reputation: 14292

Here is my code.

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
     self.scoutPropertyTable.rowHeight = UITableViewAutomaticDimension + 35
    return self.scoutPropertyTable.rowHeight
}

Upvotes: 0

Jatin Patel - JP
Jatin Patel - JP

Reputation: 3733

Actually i have download your source code and doing following changes. and UILabel is now support multiline.

Step 1 : Removed programmatically calculate row height. that means commented heightForRowAtIndexPath in your demo.

Step 2: Set following layout constraints on UILabel in your UITableViewCell.

enter image description here

Step 3 : Set number of line to 0 in your xib.

Output :

enter image description here

Upvotes: 0

AaoIi
AaoIi

Reputation: 8396

Here we go, if you are supporting IOS 7 then you need to implement UITableViewDelegate protocol in your class and then override:

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

}

for more information about Dynamic custom UITableViewCell's height based on label text length (check this out) and you can place the code in the heightForRowAtIndexPath function: height based on label text length

Also override :

 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
       // example to return the estimated height 
        return 280
    }

Note : by supporting IOS 7 you should handle it manually. there is no such easier way as IOS 8.

But if you are only supporting IOS 8 and later then you can do it simply in the following two lines :

self.tableView.estimatedRowHeight = 280
self.tableView.rowHeight = UITableViewAutomaticDimension

Upvotes: 1

Related Questions