Y2theZ
Y2theZ

Reputation: 10402

Get the width of the cell in the heightForRowAtIndexPath method

This might be a simple question, but I have searched for hours but was unable to find the answer.

Is there a way to get the cell width in the heightForRowAtIndexPath delegate method of the UITableView?

The reason is that I need to calculate the height of a NSAttributedString using boundingRectWithSize and constraint it to the width of the cell.

Currently I am calculating it in the cellForRowAtIndexPath method and then reloading the row.

This is causing each row to refresh after calculating its height which is not a very good user experience.

So can I get the width of the cell in the heightForRowAtIndexPath

Upvotes: 2

Views: 2964

Answers (2)

Khanh Nguyen
Khanh Nguyen

Reputation: 11134

Subclass UITableViewCell and override layoutSubviews

@interface MyCell : UITableViewCell

@end

@implementation MyCell 

-(void)layoutSubviews {
    [super layoutSubviews];

    // You can get the width here using self.bounds.size.width
}

@end

As msgambel suggested, if you're using UITableViewStylePlain then just the table's width is fine. However if you're doing anything complicated within the cell, subclassing is a good idea.

Upvotes: 2

max_
max_

Reputation: 24481

There are two types of UITableView, Grouped, and Plain.

Grouped table views have cells which are smaller than the width of the table view meaning that you should find the width in your -cellForRowAtIndexPath: method by running an NSLog i.e. NSLog(@"%f", cell.contentView.frame.size.width);. You can then use this to determine the height.

Plain table views have cells which have the same width as the UITableView, and therefore, you can use the width of the table view i.e self.tableView.frame.size.width.

More can be found here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

Upvotes: 2

Related Questions