0
votes

I have a label in the UITableViewCell, and I want my height TableViewCell is auto according label height.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TWTTweetTableViewCell *cell = (TWTTweetTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TWTTweetTableViewCell" forIndexPath:indexPath];

TWTTweet *tweet = self.tweets[indexPath.row];
cell.tweetMessage.text = tweet.tweetMessage;
cell.timestamp.text = [tweet howLongAgo];

cell.tag = indexPath.row;

TWTUser *user = [[TWTTwitterAPI sharedInstance] userForId:tweet.userId];
cell.user.text = user.username;

return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 165; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Tapped a tweet }

3
you are using autolayout ???EI Captain v2.0
than just return UITableViewAutomaticDimension in heightForRowAtIndexPath .. but condition is your constraints should attached properlyEI Captain v2.0

3 Answers

4
votes

for dynamically height for UITableViewCell set in viewDidLoad

_tableView.estimatedRowHeight = 100.0;
_tableView.rowHeight = UITableViewAutomaticDimension;

this set automatic cell height as per content height

Let me know if this works...

https://stackoverflow.com/a/35055320/5085393

or as method for Automatic Dimension

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}

 -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
0
votes

To get dynamically updated height

-add these methods

===========

Objective C

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

======

Swift

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

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
0
votes

First go to the UITableViewCell label's attribute inspector on the storyboard and set the Line Break property to Word Wrap. Now the constraint's for the label are important.

enter image description here

Give only Top, Bottom, Leading, Trailing constraint, this way the cell can adjust its height based on the content of the label.

Then either in your viewDidLoad or the place where you set delegate for the tableview add the below code,

self.yourTableView.estimatedRowHeight = 52.0; // Your desired minimum height for the cell.
self.yourTableView.rowHeight = UITableViewAutomaticDimension;