iPhone UITableView Nested Sections - iphone

For the acani iPhone app, I'd like display groups (based on interests) in a UITableView. I'd like to organize the groups taxonomically, e.g.:
Sports
Bat-and-ball
Baseball
Softball
Cricket
Hockey
Field Hockey
Ice Hockey
Roller Hockey
Engineering
Electrical Engineering
Biochemical Engineering
How should I arrange this on a UITableView?
I'm thinking that there should be a root UITableView that will have the sections Sports & Engineering, and the cells Bat-and-ball & Hockey will be under the Sports section, and the cells Electrical Engineering & Biochemical Engineering will be under the Engineering section.
Then Bat-and-ball should have its own UITableView, which should have cells Baseball, Softball, and Cricket.
Does this sound like a good way to arrange the UI?
Do you have any sample code or links to Xcode sample code for a UI like this? There's gotta be an Xcode sample project that does something like this. Perhaps the periodic table of elements project or Core Data Books?
Thanks!
Matt

You got it. A UITableView really isn't designed to show more than two levels of a hierarchy, as sections and rows. If you want to show more than two levels, a "drill-down" approach used in most (all?) iOS apps, where tapping a row presents another UITableView on the navigation stack. (As you say.)
There are lots of Apple sample code projects that use this design pattern.
Edit: just checked and DrillDownSave is a good example, as is SimpleDrillDown.

The trick to have nested sections is to have two kinds of rows in the table view. One to represent the second level of sections and another to represent the normal rows in the tableview. Let's say you have a two level array (say sections) to represent the items in your table view.
Then, the total number of sections that we have are just the number of top level sections. The number of rows in each top level section would be the number of subsections + the number of rows in each subsection.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionItems = self.sections[(NSUInteger) section];
    NSUInteger numberOfRows = sectionItems.count; // For second level section headers
    for (NSArray *rowItems  in sectionItems) {
        numberOfRows += rowItems.count; // For actual table rows
    }
    return numberOfRows;
}
Now, all we need to think about is how to create the rows for the table view. Set up two prototypes in the storyboard with different reuse identifiers, one for the section header and another for row item and just instantiate the correct one based on the asked index in the data source method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section];
    NSMutableArray *sectionHeaders = self.sectionHeaders[(NSUInteger) indexPath.section];
    NSIndexPath *itemAndSubsectionIndex = [self computeItemAndSubsectionIndexForIndexPath:indexPath];
    NSUInteger subsectionIndex = (NSUInteger) itemAndSubsectionIndex.section;
    NSInteger itemIndex = itemAndSubsectionIndex.row;
    if (itemIndex < 0) {
        // Section header
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SECTION_HEADER_CELL" forIndexPath:indexPath];
        cell.textLabel.text = sectionHeaders[subsectionIndex];
        return cell;
    } else {
        // Row Item
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ROW_CONTENT_CELL" forIndexPath:indexPath];
        cell.textLabel.text = sectionItems[subsectionIndex][itemIndex];
        return cell;
    }
}
- (NSIndexPath *)computeItemAndSubsectionIndexForIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section];
    NSInteger itemIndex = indexPath.row;
    NSUInteger subsectionIndex = 0;
    for (NSUInteger i = 0; i < sectionItems.count; ++i) {
        // First row for each section item is header
        --itemIndex;
        // Check if the item index is within this subsection's items
        NSArray *subsectionItems = sectionItems[i];
        if (itemIndex < (NSInteger) subsectionItems.count) {
            subsectionIndex = i;
            break;
        } else {
            itemIndex -= subsectionItems.count;
        }
    }
    return [NSIndexPath indexPathForRow:itemIndex inSection:subsectionIndex];
}
Here's a detailed post on how to do this.

Related

Duplicate elements in UITableView per section

I have 6 sections in a UItableView, every section displays 2 cells, normally, I want it like this:
However, here is what I have:
Every indexPath.row is duplicated in every section.
Here is the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"avenir";
Avenir *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
cell =[[Avenir alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.equipea.text=[arrayofClubA objectAtIndex:indexPath.section];
cell.equipeb.text=[arrayofClubB objectAtIndex:indexPath.section ];
return cell;
}
The elements are retrieved from two NSMutableArrays, one for the first left element in cell and the other for the right element cell.
What is wrong?
Thank you for helping.
You need to calculate the correct index from both the row and the column. Since you have two pairs of rows per section, you need to multiply section by two, and add row, which will be either zero or one. The end result should look like this:
NSUinteger pos = indexPath.section*2 + indexPath.row;
cell.equipea.text=[arrayofClubA objectAtIndex:pos];
cell.equipeb.text=[arrayofClubB objectAtIndex:pos];
You're always fetching the identical text for each section, since
cell.equipea.text=[arrayofClubA objectAtIndex:indexPath.section];
always returns the same value for each section (since indexPath.section contains the section's index). Perhaps you wanted to do to the following instead?
cell.equipea.text=[arrayofClubA objectAtIndex:indexPath.row];
Also, for these kind of uses, it might be a lot more straight forward to use the free Sensible TableView framework as it automatically handles displaying your arrays.

Populating UITableView row 0 static and the rest with NSArray

In one section of my app I have a UITableView which is working fine right now. I would like to set row 0 cell.textLabel.text to #"Some string". Once row 0 has been set I would then like to load the rest of the rows from an array. Currently on load my array populates the table view but I'm trying to set row 0 as a sticky. The closest example I can think of is a forum topic that is set to stay at the top. My array is constructed of returned data from a web service call.
It's been a while since I've messed with table views, and I'm having a blank on this one.
The table view is 1 section, and I get the rows by counting the elements in the array. Since I would like to create an additional cell (row 0) I would call [array count] + 1. I don't know if this approach is the best one which is why I'm reaching out to the community here.
Any insight or a shove in the right direction would be great at this point.
You're on the right track:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [array count]+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if ([indexPath row] == 0) {
// Code for first
[[cell textLabel] setText:#"First cell"];
} else {
[[cell textLabel] setText:[array objectAtIndex:[indexPath row]-1]];
}
return cell;
}
If you want the top of your table to be "sticky", why not consider using that string as a section header or title? In this case, the header stays visible at all times until the next section (e.g. if you had two sections, that is) is fully on the screen.
In any event, in one of my current projects I'm required to do roughly the same thing that you're doing and I have a static string being returned in row 0 (which scrolls off the top of screen when the table view scrolls down).
And in my UITableViewDataSource method, I always add one for the static cell to the number of objects in my array and in my "cellForRowAtIndexPath:" method, I increment the row by one when the indexPath.row is not zero. And if it is zero, I return my static string.
And dark_knight provides some nice sample code that illustrates what I was describing to you. So +1 to him/her.

Displaying a "No rows found" message in UITableView with Core Data

I have implemented an iPhone app that uses UITableViewController/UITableView and Core Data. Further, I use a NSFetchedResultsController to manage the table data. This was all very straight forward and works great. I then decided that I should display a message in the UITableView when no rows where found/retrieved. After researching this, it appeared that the best way (perhaps the only way) to do this was to return a "dummy" cell that contains the message. However, when I do this, I get a nastygram from the runtime system that complains (and rightfully so) about data inconsistencies: "Invalid update: invalid number of sections. The number of sections contained in the table view ...". Here is the relevant code:
- (NSInteger) numberOfSectionsInTableView: (UITableView *)tableView
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
return [[self.fetchedResultsController sections] count];
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex: section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *) tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) {
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = #"No widgets found.";
return cell;
}
STCellView *cell = (STCellView *)[tableView dequeueReusableCellWithIdentifier: #"ShieldCell"];
[self configureCell: cell atIndexPath: indexPath];
return cell;
}
I have read responses from similar questions and it appears that I should use
insertRowsAtIndexPaths: withRowAnimation:
to insert the "dummy" message row into my table. However, this also means removing the "dummy" row when a real row is inserted. I can do this, but it seems like there should be an easier way to accomplish this. All I want to do, is to display a message indicating that there are no rows in the table (simple enough?). So, my question is this: Is there a way to display a message in an UITableView without using the "dummy" cell approach OR is there a way to convince UITableViewController/NSFetchResulsController that this is only a "dummy" row and they should not get so upset about it because it is not a real row (from my point of view) in the table?
Any help you can provide would be very appreciated (I am a struggling newbie to iPhone development and I want to learn the best practices). Thanks.
Rather than hack with the tableview datasource to get the intended UI you should add the "No rows found" message to the tableview header instead.
I did as follows in viewDidLoad.
UILabel *label = [[UILabel alloc] init];
[label setTextColor:[UIColor lightGrayColor]];
[label setText:#"No widgets found."];
[label sizeToFit];
label.frame = CGRectMake((self.tableView.bounds.size.width - label.bounds.size.width) / 2.0f,
(self.tableView.rowHeight - label.bounds.size.height) / 2.0f,
label.bounds.size.width,
label.bounds.size.height);
[self.tableView insertSubview:label atIndex:0];
In this case, each TableViewCells must be opaque to hide the label. or need to toggle the hidden property of the label according to the row count.
An alternative approach, which I have used before is to use Core Data to manage the update for you by inserting a 'no rows' entity for the section where no rows have been detected in your model class, which handles the data update.
There are a number of ways to implement this e.g. set the name/title field to a known status message or a flag within the entity. Once inserted you can detect the 'no rows' entity in the cellForRowAtIndexPath delegate method and insert an alternative table cell to show the message.
Just remove the 'no rows' entity before refreshing the data for that section.
My simple suggestion to display an empty message is to rearrange your controller to be a simple UIViewController (not a UITableViewController).
This UIViewController is composed by a UITableView (the controller is the data source and the delegate for your table) and by a UILabel (or a UIView that contains a UILabel) that displays the empty row message.
In this manner you can control the visibility of the table and the label based on the retrieved rows.
This approach could be laborious but I think it's good to avoid hacking NSFetchResultsController and data source. Furthermore you could have a complete control on arranging the position for your empty message.
As #Rog suggested you could also use the table view header to display that message. As you prefer.
Hope it helps.

Section index in table view

I am implementing a table index view and amazed to see how my table indexes are working even without implementing:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index method.
I have only implemented:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
Strangely, when I am running in breakpoints, Once i click on any of the index values my
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method is getting called.
Any clue why this is so happening and what is the significance of sectionForSectionIndexTitle method then.
if you have a list of all letters in alphabet and your list only contains some entries, you could use the following code:
//Asks the data source to return the index of the section having the given title and section title index.
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if (tableView == self.searchDisplayController.searchResultsTableView || self.searchBar.text.length > 0)
{
return 0;
}
else
{
//direct - firsttime match
if([self.realMIndexArray containsObject:title]) {
NSInteger count = 0;
for(NSString *character in self.realMIndexArray)
{
if([character isEqualToString:title]){
return count;
}
count ++;
}
}
else {
//take next higher letter from alphabet and check if its contained in the "available letters list"
//if not, select last entry of list
for(int i = [self.indexArray indexOfObject:title] + 1; i < [self.indexArray count]; i++) {
NSString* character = [self.indexArray objectAtIndex:i];
if([self.realMIndexArray containsObject:character]) {
return [self.realMIndexArray indexOfObject:character];
}
}
return [self.realMIndexArray count] - 1;
}
return 0;// in case of some eror donot crash d application
}
}
realMIndexArray count == letters really existing in list
indexArray = list of all letters in alphbeth.
hope this helps someone (took me a little bit of time to figure it out)
Any clue why this is so happening
Yes. When you tap (you do not click on an iPhone) on a table's index, the underlying table view will want to jump to that section, and the cells in that section. In order to do that, it has to ask the data source for those cells so it can render them on the screen.
what is the significance of
sectionForSectionIndexTitle method
then.
The documentation for tableView:sectionForSectionIndexTitle:atIndex: (which is an optional method in the UITableViewDataSource protocol) says:
Asks the data source to return the
index of the section having the given
title and section title index.
and
You implement this method only for
table views with a section index
list—which can only be table views
created in the plain style
(UITableViewStylePlain).
Does this apply for your UITableView? In other words, are you using a grouped table view style?

iPhone UITableView with index can I push a different detailed view with every different cell?

I know its possible to create a table that has an index on the side and a search bar at the top that a user can type in to find an item, but is it possible to say to the table if array isEqual to "item1" push view1? I would like to push a different view with each cell. Anyone have any advice?
Sure. Just create the appropriate view (controller) depending on the cell's indexPath in tableView:didSelectRowAtIndexPath:.
Create the cell based on the index path. If you create all the cells ahead of time, store them in an array by row index. If you are creating them as needed, do something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *result;
switch ( [indexPath row] ) {
default: result = [self tableView:tableView normalCellForRowAtIndexPath:indexPath]; break;
case 3: result = [self tableView:tableView detail3CellForRowAtIndexPath:indexPath]; break;
case 5: result = [self tableView:tableView detail5CellForRowAtIndexPath:indexPath]; break;
}
return result;
}
Check out the sample programs from the book Beginning iPhone Development. You must sign up, but its free. You should look specifically at chapter 9's sample code called Nav. Shows you exactly what you need. This was my first book on the subject and was well worth it.
http://www.iphonedevbook.com/forum/viewforum.php?sid=3010c045df967353c6b3894889e6b8f5
Cheers!
Ken