How To Fetch the value Section wise in UItableview? - iphone

I am trying to make an app in which i use the Grouped Table view .In that I am creating the sections in which the first letter comes from an array and it is doing perfectly.
the code is below
sections=[[NSMutableArray alloc] init];
for(int i=0;i<[PdfNames count]; i++)
{
NSString *s=[[PdfNames objectAtIndex:i] substringToIndex:1];
NSPredicate *p=[NSPredicate predicateWithFormat:#"letter like '%#'",s];
NSArray *check=[sections filteredArrayUsingPredicate:p];
if([check count]<1)
{
dict=[[[NSMutableDictionary alloc] init] autorelease];
[dict setValue:s forKey:#"letter"];
[sections addObject:dict];
}
}
But now i am not able to get that hoe can i get the names of pdf from array which belongs to their secion Or starts with that alphabet.

You are creating an array sections which is of course empty. You then create an array check based on sections. It will therefore also be empty. [check count] will always be zero. No NSDictionary is going to be created.
Clear?

Try following code its basic logic, I hope you can understand.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0) {
return 10; // Number of rows in section.
} else if (section == 1) {
return 5;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2; // Let say we have two section.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (indexPath.section == 0) {
// Assign your data
} else if (section == 1) {
// Assign your data
}
}
Similarly you can check for the table section on didSelectRowAtIndexPath: method

Related

Adding a search bar to iPhone application that uses alphabetical sections?

I have an application that uses a UITableView which contains the names of products, these products are also split up into their respective sections based on their first letter.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
//Initialize alphabet array
m_Alphabet = [[NSArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K", #"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",#"Other", nil];
//Initialize alphabet distionary of arrays
m_AlphabetDictionary = [[NSMutableArray alloc]init];
//Populate distionary with a mutable array for each character
//in the alphabet (plus one "Other" category)
for (int i = 0; i < 27; i++)
[m_AlphabetDictionary insertObject:[[NSMutableArray alloc] init] atIndex: i];
// The number of products in the database
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
//For each product in the appDelgates products
for (Product *product in appDelegate.m_Products){
if ([product.category isEqualToString:productType]){
[tempArray addObject:product];
//firstLetter is equal to the first letter of the products name
NSString * l_FirstLetter = [product.name substringToIndex:1];
//convert firstString to uppercase
l_FirstLetter = [l_FirstLetter uppercaseString];
//The added flag ensures objects whose first letter isn't a letter
//are added to array 26
bool added = NO;
for(int i=0; i<[m_Alphabet count]; i++){
//If the first letter of product name is equal to the letter at index i in theAlphabet
if ([l_FirstLetter isEqualToString:[m_Alphabet objectAtIndex:i]]) {
//Add product to section array for that letter
[[m_AlphabetDictionary objectAtIndex:i] addObject:product];
added = YES;
}
}
//If product hasn't been added to array, add it to "Others" category
if(!added)
[[m_AlphabetDictionary objectAtIndex:26] addObject:product];
}
}
//Set navigation controller title
self.title = productType;
}
//Number of sections is equal to the length of the m_Alphabet array
//Letters A-Z plus "Other"
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [m_Alphabet count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[m_AlphabetDictionary objectAtIndex:section] count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return m_Alphabet;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [m_Alphabet indexOfObject:title];
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
if ([[m_AlphabetDictionary objectAtIndex:section] count]==0)
return nil;
return [m_Alphabet objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Cell for row");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if([self.productType isEqualToString:#"All"]){
Product *product = (Product *) [appDelegate.m_Products objectAtIndex:indexPath.row];
cell.textLabel.text = product.name;
// Configure the cell.
return cell;
}
else {
//Instead of using appDelegate.products use the new array that will be filled
//by the numberOfReowsInSection method
Product *product = (Product *)[[m_AlphabetDictionary objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = product.name;
// Configure the cell.
return cell;
}
}
What I'm looking to do is add a search bar to the top of my table view that behaves just like the search bar in the "All Contacts" section in the iPhones contacts application. I.E. When I search, all the sections disappear and just the search results are displayed until the search bar is blank again.
Can anyone point me in the right direction?
Thanks,
Jack
Looks like you need to uses UISearchDisplayController, which is most likely what the contacts application uses (along with mail, maps, safari, and music). It presents itself as a table view overlay that may or may not contain a scope bar (your choice) and filters results based on the search bar's text. A simple tutorial involving interface builder may be found here, and an apple example sans-IB may be found here.

Trying to group my table view with custom groupings (xcode 4.2 iOS 5.0)

I am writing an iPhone application and I have a table view that is populated by information I feed it from txt files. I would like to group the tables (so like by name for contacts), however I would like to choose which fields go in which grouping.
For instance, for my app, I want to group ingredients by type (so dairy products, produce, etc...) and have the corresponding ingredients appear there. How would I do that? I have this code currently for my table view:
NSString *wellBalancedIngredientFileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Well Balanced Ingredients" ofType:#"txt"] encoding:NSUTF8StringEncoding error:NULL];
wellBalancedIngredients = [wellBalancedIngredientFileContents componentsSeparatedByString:#"(penguins)"];
wellBalancedIngredients (as one of the arrays) is an array that will contain all of the "well balanced ingredients". I have 3 other arrays that I also populate the tableview with depending on user choice.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (ingredientListChoice == 1) {
return [self.wellBalancedIngredients count];
}
else if (ingredientListChoice == 2) {
return [self.meatIngredients count];
}
else if (ingredientListChoice == 3) {
return [self.vegetarianIngredients count];
}
else {
return [self.veganIngredients count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (ingredientListChoice == 1) {
cell.textLabel.text = [self.wellBalancedIngredients objectAtIndex:indexPath.row];
}
else if (ingredientListChoice == 2) {
cell.textLabel.text = [self.meatIngredients objectAtIndex:indexPath.row];
}
else if (ingredientListChoice == 3) {
cell.textLabel.text = [self.vegetarianIngredients objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [self.veganIngredients objectAtIndex:indexPath.row];
}
return cell;
// Configure the cell...
}
How do I add to this code to add the grouping into sections and then being able to have custom headings and me populating each section according to my chosen preference. Thank you for your help.
First, you should return the number of sections you want in the table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return numberOfSections;
}
Then, for the title of each section you can use:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #"Section Title";
}

Hiding UITableViewCell

Is there a way to hide a UITableView cell? I'm looking for some property or method I can invoke on the UITableViewCell returned by a synchronous cellForRowAtIndexPath() to hide it and make it unselectable by the user.
For me using mapping is not easy way, so I decided to use SAS method. But it doesn't work with my custom cell. So, I correct it:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 7 && hide7Row){
UITableViewCell* cell = [cells objectAtIndex:indexPath.row];
cell.hidden = YES;
return 0.0;
}
else if(indexPath.row == 8 && hide8Row){
UITableViewCell* cell = [cells objectAtIndex:indexPath.row];
cell.hidden = YES;
return 0.0;
}
else {
return 44.0;
}
}
Works Fine.
You mean to leave a gap in the table where the cell should be, or just to progress from the one before it straight to the one after it? In the former case, I guess you might try getting the cell's contentView and set its hidden property to YES; otherwise, you'll just have to do a little logic in your -tableView:numberOfRowsInSection: and -tableView:cellForRowAtIndexPath: methods, returning (the number of cells you'd otherwise return - 1) from the first, and, depending on whether the row index is less than or greater than the row you're not including, either (the cell you'd otherwise return) or (the cell at (the row index + 1)), respectively.
(edit, because the explanation was convoluted:)
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
if(section == theSectionWithoutARow)
{
if(shouldRemoveTheRow)
return [theArrayWithTheSectionContents count] - 1;
else
return [theArrayWithTheSectionContents count];
}
// other sections, whatever
}
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// blah blah standard table cell creation
id theCellObject;
if(indexPath.section == theSectionWithoutARow)
{
NSInteger theActualRowToDisplay = indexPath.row;
if(shouldRemoveTheRow && indexPath.row >= theRowIndexToRemove)
{
theActualRowToDisplay = indexPath.row + 1;
}
theCellObject = [theArrayWithTheSectionContents objectAtIndex:theActualRowToDisplay];
}
// now set up the cell with theCellObject
return cell;
}
There is no method to do that on the cellForRowAtIndexPath as far as I am aware.
Noah Witherspoon's method seems to be more or less workable, although it will need to be modified if you want multiple rows to be hidden.
Another way to approach it is to create a "cell map", I don't know if this is more efficient or not, but I've used it and it worked.
Let us say you have an NSArray (or mutable version thereof) of data which is to be shown in your TableView. The array's count property is used as the return value for your numberOfRowsInSection delegate method. This is a somewhat typical approach to my knowledge.
To make it so that only some of the rows are shown, I created a "mapping array", which is an NSMutableArray that contains "pointers" to your actual data array. The map contains integers wrapped in NSNumbers. In its virgin state the map's index 0 has the integer 0 (wrapped in NSNumber), index 1 has integer 1, etc.
The UITableView delegate methods are built so that the map's index count is used for numberOfRowsInSection. In the cellForRowAtIndexPath method, it looks at the appropriate index of the map array, retrieves whatever is wrapped in the NSNumber, and then looks in that index of your actual data array.
The benefit of this dereference is that it becomes extremely easy to add and remove cells from the table. Just add/remove the NSNumber objects from your mapping array. Make sense? Sorry, not at my Mac or I could just put up some code samples.
Oh, and don't forget that you have to call the update method (the exact name escapes me) on your TableView so that it refreshes and the cells hide/unhide.
Had the same problem, and as I wanted to avoid some mapping as mentioned, I just set the cell-size to 0:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row=[indexPath row];
float ret=0.0;
if( row==3) {
ret=0.0;
}
else {
ret=40.0;
}
return ret;
}
I used Matt's technique to create a mapping to cell data. Here is some code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return computeNumberOfRowsAndMapCellData;
}
// Compute mapToCellData to map the index of the cell to the cell data for the
// cell based on TaskConfig show/hide.
// Return the number of rows in section 1.
- (NSInteger)computeNumberOfRowsAndMapCellData {
if (mapToCellData) {
[mapToCellData release];
}
mapToCellData =[[NSMutableArray alloc] init];
if (cellData) {
[cellData release];
}
cellData = [[NSMutableArray alloc] init];
NSInteger numberOfRows = 12; // maximum number of rows
NSNumber *index = [NSNumber numberWithInt:0];
// If the data is not configured to show, decrement the number of rows in the table.
if ( ! [configManager isShowDateForType:task.case_type severity:task.severity]) {
numberOfRows--;
} else {
// Add a map to the cell data with the row number.
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[df stringFromDate:task.respond_due_date], #"Respond Due", nil];
[cellData addObject:dict];
[mapToCellData addObject:index];
int value = [index intValue];
index = [NSNumber numberWithInt:value + 1];
}
// Check the configuration for the rest of the rows of cell data.
....
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:15];
cell.detailTextLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14];
}
NSUInteger mapIndex = 0;
// Use the mapToCellData to find cell data based on show/hide in ConfigManager for the data type.
mapIndex = [indexPath row];
NSNumber *cellDataIndex = [mapToCellData objectAtIndex:mapIndex];
NSDictionary *cellDataDict = [cellData objectAtIndex:[cellDataIndex unsignedIntegerValue]];
cell.textLabel.text = = [[cellDataDict allValues] objectAtIndex:0];
cell.detailTextLabel.text = [[cellDataDict allKeys] objectAtIndex:0];

Customize a data-driven TableView

I have a grouped tableview that is populated with XML data in one section. What I would like to do is create another section prior to the data driven one, and apply an action to it.
Example:
The user is presented with a button that says "use your current location" (manually created section) and below that is a list of countries the user can alternatively choose from choose from (data driven section)
Use the settings menu as a guide. There are some options which are a single row in a section, so they appear to be a button...
If this doesn't make sense, I will try to explain it better.
So I have these two obvious lines of code...simple enough
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [countrysData count];
}
What I would like is to have numberOfSectionsInTableView return 2 and have the first "Section" say "Click to use your current location" which would then push into view a map, and the second section display the list of countries I currently have working.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0){
return 1;
}else{
return [countrysData count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
then you should choose what to do in your didSelectRowAtIndexPath: method due to the indexPath.section. oh, and you should check indexPath.section in your cellForRowAtIndexPath: method.
You just need to update all of your implementations of the UITableViewDataSource and UITableViewDelegate protocols to appropriately account for the new section and its row(s).
For example, here's how to update numberOfSectionsInTableView:, tableView:numberOfRowsInSection:, and tableView:cellForRowAtIndexPath:, but you will want to update at least tableView:didSelectRowAtIndexPath: as well:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// calculate the number of sections of non-data (might just be 1)
// calculate the number of sections for the data (you were already doing this, might just be 1)
// return the sum
return 1 + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger rowCount = 0;
switch (section) {
case 0:
// non-data section has 1 row/cell
rowCount = 1;
break;
case 1:
// data section uses an array
rowCount = [dataArray count];
break;
}
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *nonDataCellID = #"NonDataCell";
static NSString *dataCellID = #"DataCell";
UITableViewCell *cell;
int section = [indexPath indexAtPosition:0];
int row = [indexPath indexAtPosition:1];
switch (section) {
case 0:
// or you can just use standard cells here
cell = [tableView dequeueReusableCellWithIdentifier:nonDataCellID];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"NonDataCell" owner:self options:NULL];
cell = nonDataCell; // nonDataCell is an IBOutlet to this custom cell
}
// configure non-data cell here (use tags)
UILabel *someLabel = (UILabel*)[cell viewWithTag:1];
someLabel.text = #"Non-data cell";
break;
case 1:
// or you can just use standard cells here
cell = [tableView dequeueReusableCellWithIdentifier:dataCellID];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"dataCell" owner:self options:NULL];
cell = dataCell; // dataCell is an IBOutlet to this custom cell
}
// configure data call here (using "row")
UILabel *someDataLabel = (UILabel*)[cell viewWithTag:1];
someDataLabel.text = [[dataArray objectAtIndex:row] valueForKey:#"name"];
break;
}
return cell;
}
I'm pretty sure you can alter the return of UITableViewDataSource's method 'numberOfSectionsInTableView:' on the fly. Once the user selects the choice of an additional section, just set a flag to have the method return the number of tables you want. Then you force a reload of the table and you should see the new section.

Adding data to 2 Sections of UITableView from SINGLE nsmutablearray

I wanted to know how to list data in tableView in different sections BUT from a single datasource.
All examples i saw had number of arrays = number of sections. What i want is suppose I have a 3d nsmutableArray.
If dArray.Id = 1 { //add to first section of UITableView }
else add to Section 2 of UITableView.
Its probably dooable, but i jus need a direction.
Yeah it is possible to do it.
You can have a single NSMutableArray (resultArray) with the entire content in it.
Then in the cellForRowAtIndexPath method you can do it this way
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0)
{
cell.text=[resultArray objectAtIndex:indexPath.row];
}
else if(indexPath.section == 1)
{
cell.text=[resultArray objectAtIndex:(indexPath.row+5)];
}
else if(indexPath.section == 2)
{
cell.text=[resultArray objectAtIndex:(indexPath.row+11)];
}
}
and in numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView1 numberOfRowsInSection:(NSInteger)section {
NSInteger count;
if(section == 0)
{
count=6;
}
else if(section == 1)
{
count=6;
}
else if(section == 2)
{
count=4;
}
return count;
}