Table View, Static Cells, changing Cell Height - ios

I understand that using a dynamic TableView, you can set the Cell Height using...
tableView:heightForRowAtIndexPath:
However, if I am using A Static Table View ( not Dynamic), With Sections, I would like to programmatically set the height of a cell to 0.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//used to set the height of a cell
CGFloat result;
switch(indexPath.section) {
case 0:
{
//How do I get the ROW number in this section?
result = 44;
break;
}
case 1:
{
//this works if I want to set all of the rowels to this height.
result = 250;
break;
}
}
The question asked another way, If I have the indexPath.section... how can I do something like...
indexPath.Section.row?

You can use indexpath.row directly. No need to write indexPath.Section.row.

In iOS, the NSIndexPath gets extra duties. It is a bit confusing as Apple has two different pieces of documentation.
As noted in the other answers, you get:
Getting the Section Index
section property
Getting the Index of a Row or Item
row property
item property

Related

Expand UILabel inside UITableView with "more" button like Instagram

I've got a project (that has been written by other people) where there's a feed with content and text displayed inside a table view. Each post corresponds to one section in table view, and each section has its own rows corresponding to elements like content, text, like button etc.
I need to display a short label for post captions with a "more" button inside table view cell, and when more button is tapped, the label will expand to whatever size the caption fits, all happening inside a table view cell. When the more button is tapped I change the label's numberOfLines property to zero, and as the cells have automatic height, all I need is to reload that particular caption cell. (the cell displays correctly with the expanded size if I set numberOfLines to 0 at the first place before displaying the cell.)
I've tried:
[tableView beginUpdates];
tableView endUpdates];
I've tried various animation options with:
[tableView reloadRowsAtIndexPaths:#[myPath] withRowAnimation:UITableViewRowAnimation(Bottom,Top,None etc)];
I've tried:
[tableView reloadSections:[NSIndexSet indexSetWithIndex:myPath.section] withRowAnimation:UITableViewRowAnimation(Top,Bottom,None etc)];
But they all yield the same result: the whole table view layout gets messed up: it jumps to another cell, some views go blank, cells overlap each other, video inside cells stop playing, and the label doesn't expand (but refreshes inside itself, e.g. that short preview txt with one line animates from top/bottom etc but doesn't expand).
What might be causing the mess up of the whole table view and how I can reload just one cell correctly with and expansion animation, without messing up the whole layout? I've seen many questions and answers regarding this, but they all recommend the options that I've already tried and explained above.
My app targets iOS 8.0+
UPDATE: Here is the relevant code (with some parts regarding inner workings that aren't related to layout, removed):
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier: MyCellIdentifier forIndexPath:indexPath];
cell.delegate = self;
cell.indexPathToReloadOnAnimation = indexPath;
cell.shouldShortenCaption = YES;
id post = self.posts[indexPath.section] ;
[cell setPost:post];
return cell;
And inside setPost::
if(self.shouldShortenCaption){
captionLabel.numberOfLines = 2;
}else{
captionLabel.numberOfLines = 0;
}
NSString *text = [some calculated (deterministic) text from post object];
Button action is simple:
self.shouldShortenCaption = NO;
[one of the reload codes that I've written above in the question]
UPDATE 2: Here are some more methods regarding the issue:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section < self.posts.count) {
return 59;
}else
return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (section < self.posts.count) {
MyFeedHeader *header = [tableView dequeueReusableCellWithIdentifier:MyFeedHeaderIdentifier];
header.delegate = self;
[header setPostIndex:section];
[header setPost:self.posts[section]] ;
return header;
}
else
return nil;
}
Header's setPost: method basically sets the relevant texts to labels (which have nothing to do with the caption, they are completely different cells. the problematic cell is not the header cell). The table doesn't have any footer methods. The only method regarding height is the one above.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section >= self.posts.count) {
return 1;
}
id post = self.posts[section];
[calculate number of rows, which is deterministic]
return [number of rows];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
BOOL hasCursor = self.cursor && self.hasMore ? 1 : 0;
return self.posts.count + hasCursor;
}
(Post count and cursor and hasMore are also deterministic).
UPDATE 3: I've asked a question (which wasn't a duplicate, even though there are similar questions) and got a useful answer that solved my problem. Can the downvoters please elaborate the reason that they've downvoted?
Here is an example: https://github.com/DonMag/DynamicCellHeight
Table B is one way of accomplishing "More/Less" (Table A was for another layout I played around with). It uses the [tableView beginUpdates]; tableView endUpdates]; method of triggering the table re-layout.
The key is getting all your constraints set up correctly, so the Auto-Layout engine does what you expect.
The example is in Swift, but should be really easily translated back to Obj-C (I think I did it in Obj-C first).
Edit: some additional notes...
This is using a pretty standard method of dynamic-height table view cells. The vertical spacing constraints between elements effectively "pushes out" the bounds of the cell. The tap here toggles the numberOfLines property of the label between 2 and 0 (zero meaning as many lines as necessary). Sequential calls to beginUpdates / endUpdates on the table view tells the auto-layout engine to recalculate the row heights without needing to reload the data.
For this example, I did use a little "trickery" to get the smooth expand/collapse effect... The multiline label you see here is contained in a UIView (with clipsToBounds true). There is a second, duplicate multiline label (alpha 0 so it's not visible) that is controlling the height. I found that changing the numberOfLines on the visible label sort of "snapped" to 2 lines, and then the size change animation took place... resulting in the text "jumping around."
Just for the heck of it, I added the "not so good" version to my GitHub repo for comparison's sake.

Static UITableView with custom row heights

I'm trying to create detail view controller as a list of information and I think it would be nice and clean to present this with a static UITableView. But after that it came to my mind that on some level it might be difficult, so please resolve my doubts!
Every UITableViewCell has different style (some are custom, some are basic and few are right-detailed etc.).
What is more, content size of each cell may vary as I have long names put inside labels so they use autolayout to fit.
There is no problem when I have the same cells repeating but with different tex inside UILabels. In that case I use a simple:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.prototypeCell) {
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:#"ActivityCell"];
}
[self fetchedResultsController:[self fetchedResultsController] configureCell:self.prototypeCell atIndexPath:indexPath];
CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
I don't know how to deal with heightForRowAtIndexPath. I can give an identifier to each cell, call cellForRowAtIndexPath:, and make a big switch or if statement, but is it right? The same problem occurs while I think of cellForRowAtIndexPath: and populating those UITableViewCells. With those testing statements this code won't be pretty and readable.
Any ideas on that case?
In the delegate function of the table view named heightForRowAtIndexPath try to calculate the height for each row and then return it.
//return height for row
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView==tblLanguage)
{
//Here calculate the dynamic height according to songs count for specific language
return (([[arrSongListForSpecificLanguage objectAtIndex:indexPath.row] count]*40)+40);
}
return 40.0;
}

Change the height of a static UITableViewCell only possible by overriding heightForRowAtIndexPath?

I've looked through lots of examples of how to hide a static UITableViewCell by overridding heightForRowAtIndexPath, and while I've now got it working it just seems so cumbersome that I'd like to see if I'm doing something wrong.
I have a UITableViewController with a table view that has about 8 rows. This screen in my app shows a single object, so for example one row is description, one is an image, one holds a map view, etc. All of the rows are static.
In some cases, some of the objects that are shown don't have a map, so I want to hide the row that holds the mapview. Since it's a static row, I was thinking that by having an outlet property for that row (e.g. #property (weak, nonatomic) IBOutlet UITableViewCell *mapViewRow;), then I could somehow set that row's height to 0 or hide that row in viewDidLoad or viewWillAppear. However, it seems like the only way to do this is to override the heightForRowAtIndexPath method, which is kind of annoying because then I need to hardcode the index of the map row in my code, e.g.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 6 && self.displayItem.shouldHideMap) {
return 0;
}
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
Of course, not a big deal, but just the whole way of sizing static rows in a tableview seems like it defeats the point of setting them up in the storyboard in the first place.
EDIT - rationale behind my answer
To change the height of a row you must reload either the whole table or a subset containing that row. B/c it's a bit odd to have a row in the table w/ zero height, I prefer modifying your data source such that the row doesn't exist in the table.
There are a number of ways to do that. You could build an array from your displayItem where each row in the array corresponds to a row in the table w/ appropriate data. You would rebuild this array and then call [tableView reloadData]. My original answer would also eliminate the unwanted row by treating each data element as a section with 0 or 1 rows.
ORIGINAL ANSWER
Is your tableview a plain or grouped style? If it's a plain style, you could treat each row as a section with either 0 or 1 rows in it. In your tableView dataSource and delegate methods you would use the section index to identify the data within self.displayItem that you care about for that section.
Your code would be something like:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 8; // max number of possible rows in table
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = 1;
// set self.mapSectionIndex during initialization or hard code it
if (section == self.mapSectionIndex && self.displayItem.shouldHideMap) {
rows = 0;
}
return rows;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:indexPath
{
return 60.0f; // whatever you want the height to be
}
// also modify tableView:cellForRowAtIndexPath: and any other tableView delegate and dataSource methods appropriately
you can override heightForRowAtIndexPath and just write in it return UITableViewAutomaticDimension; this will make cell calculate the height automatically as UILabel height is >= . it worked for me.

UITableView returning wrong indexPath when moving cells between sections

I'm creating a list app where the user can check off items, the checked items move to the bottom (a different section in the UITableView) when checked after a short delay. The user can "uncheck" the item by tapping it and it moves back to the original section.
My problem is that when the cells are moving between sections like this it seems the UITableView get "confused" about where which cells are.
When I NSLog the IndexPath.row of the cell I'm interacting with it returns a different row than I'm touching. I use [self.tableView moveRowAtIndexPath:from_indexPath toIndexPath:to_indexPath]; to move the cells between sections. Here's some of my code:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
switch (indexPath.section) {
case SECTION_ACTIVE:{
ItemData *dataForCell = [activeList objectAtIndex:indexPath.row];
NSLog(#"%# \t %d",dataForCell.title, indexPath.row);
if (dataForCell.isHeader) {
NSLog(#"%d",indexPath.row);
return 70;
}
break;
}
default:
break;
}
return 55;
}
Is there any way to work around this? Or to fix this?
You can tag your table cells and can re-check it when you move your cell from one section to another.

heightForRowatIndexPath does not set cell height

I am trying to create a grouped table view with 3 groups, and each group has cells that are a different height. I've set up 3 prototype cells in my Storyboard with the appropriate heights, and have set up my UITableViewController to return the appropriate heights for each row. However for some reason all of my cells are only 1 pixel tall when they appear on screen.
I've stepped through the code and the correct height and cell is returned for each row. I've also verified that the frame of each cell is correct before it is returned. However calling rectForRowAtIndexPath reveals that the rect for each row is only 1 pixel tall.
This problem goes away entirely when using a constant cell height. In that situation the cells display perfectly, some of them are just too short/tall since they should be variable height.
Any ideas what is going on here? I'd like to undertand how the rect for each row is determined when using heightForRowAtIndexPath.
Code for heightForRowAtIndexPath:
- (NSInteger)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
case 0:
return 80.0;
break;
case 1:
return 260.0;
break;
case 2:
return 110.0;
break;
case 3:
return 114.0;
break;
default:
break;
}
return 0;
}
You have declared tableView:heightForRowAtIndexPath: to return NSInteger.
That should be CGFloat.
simply to increase the height for row .simply write the method for height for row at indexpath an simply written
if (indexpath.section== 0)
return 50;

Resources