Why is a UITableViewCell 1px taller than the row height? - iphone

I have a UITableViewController. In viewDidLoad I set the rowHeight:
self.tableView.rowHeight = 43;
But then in cellForRowAtIndexPath, I check the height of the cell:
NSLog(#"bounds: w = %f, h = %f", cell.bounds.size.width, cell.bounds.size.height);
This prints a height of 44 and a width of 320. Anyone know why it would print a height of 44 instead of 43?
Thanks!

Simply put, the two things are independent of each other.
When you set rowHeight in your UITableView object, you are telling it how to render the table. The default value for rowHeight is 44.
When you create a UITableViewCell object, as a subclass of UIView, it has its own default frame and bounds, which includes a height (and width). The default value for height also just happens to be equal 44.
Your confusion arises because you have created a UITableViewCell object and you expected it to have a height equal to the (not default) rowHeight property in your UITableView object. How can it? It just came into existence!
Like all UIViews, until something comes along and explicitly changes its height, its height won't change.

1.
Do not forget about UITableView separator (separatorStyle property) ;)
it has 1 px height.
Set self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone for plain-styled tableView and you will see expected value!
Grouped TableView will always have separator and will be adjusted by 1 px.
2.
(tip) Use cell.contentView.frame (or bounds) property instead of cell.frame (or bounds)

Do you have a:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
You can implement this method to return 43 no matter what. You can also customize to your heart's content. That's why it takes a UITableView as its first argument. You could have multiple UITableViews using the same delegate.

Related

Within cellForRowAtIndexPath getting height of cell when cells are variable height

I create custom cells within my tableview some have images and are tall some are just text. The height of the cells are calculated in heightForRowAtIndexPath, which I beleive is done before cellForRowAtIndexPath is called. I want to place an imageview at the bottom of the cell regardless of heigh, but I am not sure how to get the calculated height from within cellForRowAtIndexPath?
Too late for an answer..
But, like #user216661 pointed out, the problem with taking the height of the Cell or the ContentView is that it returns the cells original height. Incase of rows with Variable height, this is an issue.
A better solution is to get the Rect of the Cell (rectForRowAtIndexPath) and then get the Height from it.
- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath {
UITableViewCell *aCell = (UITableViewCell *)[iTableView dequeueReusableCellWithIdentifier:aCellIdentifier];
if (aCell == nil) {
CGFloat aHeight = [iTableView rectForRowAtIndexPath:iIndexPath].size.height;
// Use Height as per your requirement.
}
return aCell;
}
You can ask the delegate, but you'll be asking twice since the tableView already asks and sizes the cell accordingly. It's better to find out from the cell itself...
// in cellForRowAtIndexPath:, deque or create UITableViewCell *cell
// this makes the call to heightForRow... and sizes the cell
CGFloat cellHeight = cell.contentView.bounds.size.height;
// alter the imageView y position (assuming the rest of the frame is correct)
CGRect imageFrame = myImageView.frame;
imageFrame.y = cellHeight - imageFrame.size.height; // place the bottom edge against the cell bottom
myImageView.frame = imageFrame;
You are allowed to call heightForRowAtIndexPath yourself! Just pass the indexPath from cellForRowAtIndexPath as an argument and you can know the height of the cell you are setting up.
Assuming you are using a UITableViewController, just use this inside cellForRowAtIndexPath...
float height = [self heightForRowAtIndexPath:indexPath]

dynamic uitableviewcell height according to custom cell height

I am wondering, is there a way to read the height of the custom tableview cell you are going to use in your uitableviewcell which you can then say to your uitableviewcell be this ---> height?
I am not fully understand your question but do you want to set the height for each custom cell ? If yes then you can do it by :
Let say I have custom cell at index 0 rest are my default cells or can be custom cell as well .
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0 ) {
return 105.0;
}else {
return 80.0;
}
}
No, the height that you set in the xib/storyboard is for display purposes only and doesn't transfer over to code.
The only way to change the height is from your custom subclass, by overriding tableView:heightForRowAtIndexPath:.
If you have a lot of different heights, you could always subclass UITableViewCell and add a height property which tableView:heightForRowAtIndexPath: uses when it sees your subclass. Then, in your storyboard, select your cell, go to the identity inspector, and add a User Defined Runtime Attribute for height with the value that you need.

Number of rows in UILabel

I have UITableView with custom cells, which contain uilabels.
I am using it to show comments and it must have flexible height.
How can I do it?
I have code, which counting number of rows with help of uilabel.text length, but it is wrong way. Have you any ideas?
Use UILabel with numberOfLines set to zero.
Then, for making sure that your label actually fits into the cell, get the dimensions from the NSString UIKit extension like this;
CGFloat cellWidth = 320.0f; //example width....
labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(cellWidth, FLT_MAX)];
From the NSString reference;
sizeWithFont:constrainedToSize:
Returns the size of the string if it were rendered and constrained to
the specified size.
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
Parameters font The font to use for computing the string size. size
The maximum acceptable size for the string. This value is used to
calculate where line breaks and wrapping would occur. Return Value The
width and height of the resulting string’s bounding box.
Create a class method of the comment cell class that calculates the height of text needed for cell's height. Also create a class method that returns cell's default font, so you can always calculate proper cell height in cell's layoutSubviews and in UITableViewDelegate's cellHeightForRowAtIndexPath methods.
e.g.
+(UIFont *) defaultCommentFont {
return [UIFont italicSystemFontOfSize:13];
}
+(CGSize) sizeOfComment:(NSString *)commentText maxWidth:(CGFloat)maxWidth {
return [commentText sizeWithFont:[[self class] defaultCommentFont] constrainedToSize:CGSizeMake(maxWidth, MAX_FLOAT)];
}
- (void)layoutSubviews {
[super layoutSubviews];
static CGFloat margin = <# margin #>;
CGSize commentSize = [[self class] sizeOfComment:self.commentText maxWidth:self.contentView.frame.size.width - 2 * margin];
self.commentLabel.frame = CGRectMake(margin, margin, commentSize.width, commentSize.height);
}
(sorry if there are any mistakes in the code - using only the eye-based parser ;))
Having this, when you try to return a proper height of cell in UITableViewDelegate's method, you don't have to use cellForRowAtIndexPath: method, because this, in some cases, can cause an uncontrolled recursion resulting in stack overflow.
And, like Till said, set the comment label's property numberOfLines to 0.

Get width/frame of entire UITableViewCell

I have a method where I have a (rendered) UITableViewCell*. I would like to know the width/frame of the entire cell.
cell.frame doesn't seem to work - it gives me the frame of a random cell. The closest I got is cell.contentView.frame but it doesn't include the area covered by the accessoryView (see http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7). cell.contentView.superview.frame doesn't work either - it gives me a frame at some arbitrary location just like cell.frame does.
cell.contentView.width + cell.accessoryView.width works except in cases where the accessory view is UITableViewCellAccessoryNone
Any ideas how I can get the entire frame/width of the UITableViewCell in all cases?
Try this,
NSLog(#"Cell Width = %f",cell.frame.size.width);
NSLog(#"Cell Height = %f",cell.frame.size.height);
It will show the current cell Width and Height.
This code gives you the frame of the particular cell selected by indexPath:
// Get the cell rect and adjust it to consider scroll offset
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
cellRect = CGRectMake(cellRect.origin.x - tableView.contentOffset.x, cellRect.origin.y - tableView.contentOffset.y, cellRect.size.width, cellRect.size.height);
cell.frame will always give you the frame of the cell you're messaging.
And even if it did return a random cell, you should still be able to use the width of the frame, because all the cells have the same width.
I think by default, a cell will use 100% of the width of the UITableView so a UITableView's width is equivalent to a cell's width and because you would likely have set your table cell height using:
[UITableView setRowHeight:tableCellHeight];
Where tableCellHeight is a number of your choice and UITableView is the name of your UITableView not the UITableView class itself.
Then you would have both the width and height of a table cell, or did I misinterpret your question?

How can I do variable height table cells on the iPhone properly?

My app needs to have variable height table cells (as in each table cell differs in height, not that each cell needs to be able to resize itself).
I have a solution that currently works, but it's kludgy and slow.
My Current Solution:
Before the table cells are rendered, I calculate how high each cell needs to be by calling sizing methods such as -sizeWithFont:constrainedToSize: on its data. I then add up the heights, allow for some padding and store the result with the data.
Then when my UITableViewDelegate receives the -tableview:heightForRowAtIndexPath: I work out which item will be rendered for that cell and return the height that I calculated previously.
As I said, this works, but calling -sizeWithFont:constrainedToSize: is very slow when you're doing it for hundreds of items sequentially, and I feel it can be done better.
So for this to work, I had to maintain two parts of code - one that would calculate the cell heights, and one that would actually draw the cells when the time comes.
If anything about the model item changed, I had to update both of these chunks of code, and now and again they still don't even match up perfectly, sometimes resulting in table cells that are slightly too small for a given item, or too large.
My Proposed Solution:
So I want to do away with the precalculating the cell height. A) because it breaks the MVC paradigm and B) because it's slow.
So my cell draws itself, and as a result, ends up with the correct cell height. My problem is that I have no way of telling the table view the height of the cell before its drawn - by which time its too late.
I tried calling -cellForRowAtIndexPath: from within -tableView:heightForRowAtIndexPath: but this gets stuck in an infinite loop, since the first calls the second at some point, and vice versa (at least this is what I saw when I tried it).
So that option is out of the question.
If I don't specify a size in the height for row delegate method, then the table view goes screwwy. The cells are the perfect height, but their x position is that of cells of fixed heights.
Messed Table Cells http://jamsoftonline.com/images/messed_table_cells.png
Notice how the bottom cell is the correct size - it's just overlapping the previous cell, and the previous cell overlaps its previous, and so on and so forth.
Also using this method, while scrolling there is some artifacting occurring which I think may be related to the reuse identifier for the cells.
So any help here would be gratefully appreciated.
Here's what I use. NSString has a method that will tell you the dimensions of a textbox based on the font information and the height/width constraints you give it.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [self getTextForIndexPath:indexPath];
UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [self getSizeOfText:text withFont:font];
return (size.height + 11); // I put some padding on it.
}
Then you write a method pull the text for this cell...
- (NSString *)getTextForIndexPath:(NSIndexPath *)indexPath
{
NSString *sectionHeader = [self.tableSections objectAtIndex:[indexPath section]];
NSString *sectionContent = [self.tableData objectForKey:sectionHeader];
return sectionContent;
}
And this is to get the size of the text.
- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font
{
return [text sizeWithFont:font constrainedToSize:CGSizeMake(280, 500)];
}
Just a thought:
What if you had, say, six different types of cells each with their own identifier and a fixed height. One would be for a single-line cell, the other for a two-line cell, etc...
Every time your model changes, calculate the height for that row then find the nearest cell type that has height closest to what you need. Save that celltype identifier with the model. You can also store the fixed row height for that cell in the model so you can return it in the tableview:heightForRowAtIndexPath call (I wouldn't get too hung up on forcing it to calculate inside the cell class itself--technically it's not part of the cell drawing functionality and more something the tableview uses to decide which cell type to create).
At runtime, when asked to return a cell for that row all you need to do is create (or obtain from the cell cache) a cell with the celltype identifier, load the values and you're good to go.
If the cell height calculation is too slow, then you could pull the same trick the tableview cache does and do it only on-demand when the cell comes into view. At any given time, you would only have to do it for the cells in view, and then only for a single cell as it scrolls into view at either end.
I realise this won't work for you due to the infinite loop you mention, but I've had some success with calling the cells layoutSubViews method
Though this may be a little inefficient due to multiple calls to both cellForRowAtIndexPath and layoutSubViews, I find the code is cleaner.
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
[cell layoutSubviews];
return CGRectGetHeight(cell.frame);
}
And in the layout code:
- (void)layoutSubviews
{
[super layoutSubviews];
//First expand the label to a large height to so sizeToFit isn't constrained
[self.myArbitrarilyLengthLabel setFrame:CGRectMake(self.myArbitrarilyLengthLabel.frame.origin.x,
self.myArbitrarilyLengthLabel.frame.origin.y,
self.myArbitrarilyLengthLabel.frame.size.width,
1000)];
//let sizeToFit do its magic
[self.myArbitrarilyLengthLabel sizeToFit];
//resize the cell to encompass the newly expanded label
[self setFrame:CGRectMake(self.frame.origin.x,
self.frame.origin.y,
self.frame.size.width,
CGRectGetMaxY(self.myArbitrarilyLengthLabel.frame) + 10)];
}