Get width/frame of entire UITableViewCell - iphone

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?

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]

Calculate custom cell height with multiple views iphone

I want to calculate my custom cell height with multiple subviews like labels, imageViews, buttons etc.
How do I calculate this cell size?
It seems it's not recommended to do it in cellForRowAtIndxPath, also taking an instance of Cell in heightForRowAtIndexPath, it goes in infinite loop.
I'm able to calculate the height for cell in the custom cell class but I'm not sure wheather where should I return it.
Since the method, heightForRowAtIndexPath doesn't get a cell instance, how to tell this method the type of cell for which I want to render the calculated height?
Any help is appreciated.
Thanx in advance.
Ideally, you should be able to calculate the height of the cell without having to create a cell for it. tableView:heightForRowAtIndexPath: will be called for every cell in your table (not just the ones on screen) and if you have to create a complete cell object in that method it will probably have a big impact on performance.
You have to derive the type of cell based on the indexPath argument, in the same way you do it in tableView:cellForRowAtIndexPath:
You could always load your cells in viewWillAppear or viewDidLoad, and then add them to an NSArray. Then, in tableView:heightForRowAtIndexPath:, using the provided indexPath, return the height of the relevant cell in your array. Then, in tableView:cellForRowAtIndexPath, again, using the provided indexPath, return the relevant cell in your array.
PLEASE NOTE:
If you have a lot of cells, this could cause your UI to lock up while it loads the cells. To avoid this, you could create a custom method to populate the array, and perform it on a background thread.
Also, if it takes too long, the tableView will not display all of your cells, as your array will not have been fully populated. This means that you should call [tableView reloadData]; after the array is populated.
This' how I did it:
I created an array of catgories of the cells in the order of their apearence in tableview called category_type and then I checked for the category types and calculated the height of the text-based controls to calculate the entire height of cell.
NSString *category = [NSString stringWithFormat:[category_type objectAtIndex:indexPath.row]];
if([category isEqualToString:#"xyz"])
{
xyzInstance = [arrayWithObjectsToLoad objectAtIndex:indexPath.row];
float textHeight = [MLUtils calculateHeightOfTextFromWidth:editorialInstance.eletitle : [UIFont fontWithName:#"Helvetica" size:13.0] :320 :UILineBreakModeWordWrap]; //Dyanamic label height
totalHt = 171 - 21 + textHeight + 20; // My calculation for text part of label
return totalHt;
}
I did this for all the categories.

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

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.

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)];
}

Determine coordinates of a UITableViewCell while scrolling

My goal is to have the UITableViewCells fade in/out when they are approaching the bounds of the UITableView and about to be covered/revealed.
The approach I have been trying is to get the coordinates of the UITableViewCell during a scroll event. The problem is that every cell seems to be at 0,0. I have tried converting the coordinates to the parent table and view, but they still come out at 0,0.
So in general, if anyone knows a way to get the coordinates, or of a better way to go about fading UITableViewCells in and out based on their position, I would greatly appreciate any advice you may have.
Thanks for your time,
Joel
The first step is to use
CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
which will report the CGRect of a cell within the tableView. However, this value does not change as the tableView scrolls. It is the position relative to the first row of the table (and not the first visible row). To get the position of the cell on the screen you have to convert it to the superviews coordinate system using
CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];
So the following line does it all
CGRect rect = [tableView convertRect:[tableView rectForRowAtIndexPath:indexPath] toView:[tableView superview]];
Swift 4
// Consider the indexPath at row 1, section 0.
let rectWithinTableView : CGRect = self.tableView.rectForRow(at: IndexPath(row: 1, section: 0))
let rectWithSuperViewCoordinates : CGRect = self.convert(rect: rectWithinTableView, to: self.tableView.superview)
Why not an overlay with a partially transparent gradient PNG in a UIImageView that's less translucent at the top and bottom?
Messing with cell drawing in table scrolling is going to take a big performance hit.
You can call
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;
to get the rect of any given cell. This will contain it's coordinates in the origin struct within the rect.
I suspect the cells are held within 'cell sized' subViews of the UITableView so you are seeing a frame relative to that view.
I don't have an actual an answer for you but, I would suggest checking out UIScrollView's delegate class: UIScrollViewDelegate. It responds to – scrollViewDidScroll: and you can manually work out your offset from that. UIScrollView is a superclass of UITableView.
You can convert points (such as your origin) to another view's co-ordinates using UIView's - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view method.