Custom tableview cell multiple rows - ios

This is my json data. Here it is Restaurant name coming one and line name coming 2 some times line name coming more then how to print the data in custom cell.please. help me
"currency": "$",
"state": "sale",
"total": 243.1,
"name": "a1238",
"restaurant_name": "\"Food Court\" Biergarten",
"date": "2016-10-16 07:52:07",
"table_no": null,
"so_id": 238,
"lines": [
{
"line_status": "pending",
"line_id": 2536,
"line_price": 1,
"line_qty": 1,
"line_name": "Käse"
},
{
"line_status": "pending",
"line_id": 2579,
"line_price": 7.8,
"line_qty": 2,
"line_name": "3 Musketiere (3x verschiedene Hefe 0,3l)"
},

Try like this:
First get all values from your response in NSMutableArray what you want
#interface ViewController ()
{
NSMutableArray *restaurentsNamesArray;
NSMutableArray *linesArray;
NSMutableArray *linesCountArray;
}
After that in viewDidLoad add values to those mutable arrays which you got from your response
- (void)viewDidLoad {
[super viewDidLoad];
restaurentsNamesArray = [[NSMutableArray alloc]init];
linesArray = [[NSMutableArray alloc]init];
linesCountArray = [[NSMutableArray alloc]init];
NSError *error;
// Do the stuff for get response from url here.
// And give that request below.
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary *main = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *result = [main valueForKey:#"result"];
NSArray *saleorders = [result valueForKey:#"saleorders"];
for (NSDictionary *dict in saleorders){
[restaurentsNamesArray addObject:[dict valueForKey:#"restaurant_name"]];
[linesArray addObject:[dict valueForKey:#"lines"]];
}
NSLog(#"%#",restaurentsNamesArray);
NSLog(#"%#",linesArray);
}
Now all you want is implement table view delegate methods like below:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [restaurentsNamesArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *array;
if (linesArray.count > section){
array = [linesArray objectAtIndex:section];
}
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc]init];
NSArray *array;
array = [linesArray objectAtIndex:indexPath.section];
NSDictionary *dict = [array objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"line_name"];
cell.detailTextLabel.text = [dict valueForKey:#"line_id"];
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [restaurentsNamesArray objectAtIndex:section];
}
Here I'm just populating restaurant names in tableView section header as NSString.
If you want exactly like android what you shown above you have to implement below methods instead of -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section this method
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 50)];
[headerView setBackgroundColor:[UIColor darkGrayColor]];
UILabel *tempLabel=[[UILabel alloc]initWithFrame:CGRectMake((headerView.frame.size.width/2)-47,-32,300,94)];
tempLabel.backgroundColor=[UIColor clearColor];
tempLabel.shadowColor = [UIColor blackColor];
tempLabel.shadowOffset = CGSizeMake(0,2);
tempLabel.textColor = [UIColor whiteColor];
tempLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
tempLabel.font = [UIFont boldSystemFontOfSize:17.0];
tempLabel.text= [restaurentsNamesArray objectAtIndex:section];
[headerView addSubview:tempLabel];
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
return 35;
}
Like the same way I'm just populating lineName in cell.textLabel
If you want to do more , just create custom tableViewCell and create layout how you want.
that's it.
Cheers.

Use your restaurant array for section
numberOfSectionsInTableView{}
and your "lines": [{}] array for
numberOfRowsInSection{}
You may get better idea from code mentioned below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number restaurant count
return [restaurantArray count];
}
and for multiple rows considering you have restaurant as object:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of lines count.
return [objRestaurant.Lines count];
}

First of all create an array of Restaurant type an fetch the data from json and add it into an array just like that
var RestaurantArray = [Restaurant]()
for index in 0..<JSON["data"].count
{
let address = String(JSON["data"][index]["Address"])
let CityId = JSON["data"][index]["CityId"].int
let Description = String(JSON["data"][index]["Description"])
let Name = String(JSON["data"][index]["Name"])
//create an object of Restaurant type and map the data into object and then add it into array that we have created .
var RestaurantModel:Restaurant?
RestaurantModel.address = address
RestaurantModel.cityID = cityId
RestaurantModel.Description = Description
RestaurantArray.append(RestaurantModel)
}
now use this array in your tableview
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return RestaurantArray.count
}
I hope this will make a lot of sense to you
Cheers

Related

UITableviewCell row and header are two different array

I have two array. One for Tableview Header and another one for Tableview row. I want to display header wise values for different Rows. Number of sections are depend on that array which is used in Header view.
Number of rows is calculated tableview row array divide by header array.
The UI working perfectly and also values of header and sections are fine but row values appear same for each and every section.
yo have to use this Approach to show different Cell Result
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _mutableArray.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(5, 0, tableView.frame.size.width, heightOfSection)];
NSDictionary *dict = [_mutableArray objectAtIndex:section];
NSString *useIt= [dict objectForKey:#"CategoryName"]
return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSDictionary *dict = [_mutableArray objectAtIndex:section];
NSArray *array= [dict objectForKey:#"FontNames"];
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableViewLocal cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// static NSString *cellIdentifier = #"Cell";
UITableViewCell *Cell = [tableViewLocal dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
for (__strong UIView *view in Cell.contentView.subviews) {
[view removeFromSuperview];
view = nil;
}
// [tableViewLocal setAllowsSelection:NO];
/* UILabel *labelDetailName =[[UILabel alloc]init];
labelDetailName.frame =CGRectMake(5, 15, 300, 40);
NSDictionary *dict = [_mutableArray objectAtIndex:(tableViewLocal.tag-100)];
NSArray *arrayLocal = [dict objectForKey:#"FontNames"];
NSString *titleName =[ [arrayLocal objectAtIndex:indexPath.item]objectForKey:#"title"];
labelDetailName.text = titleName;
NSString *fontName = [[arrayLocal objectAtIndex:indexPath.item] objectForKey:#"nameForSystem"];
labelDetailName.font = [UIFont fontWithName:fontName size: kSystemVersion < 7.0 ? 20 : 16];
[Cell.contentView addSubview:labelDetailName]; */
NSDictionary *dict = [_mutableArray objectAtIndex:(tableViewLocal.tag-100)];
NSArray *Array = [dict objectForKey:#"FontNames"];
NSString *localString = [Array objectAtIndex:indexPath.row]; // use it
}

Add Alphabetical Headers to UITableView with a sorted array

I'm sorting my array by last name alphabetically. I'd like to separate this into sections with the appropriate header above each section (A, B, C, etc.).
Here's what I've tried below:
// Here is where I refresh the data and sort it based on last name
- (void)refreshData {
[[PCMSSessionManager sharedSession] refreshPCMSDataWithCompletion:^(BOOL success, NSString *errorMessage, id resultObject) {
if (success) {
NSLog(#"yay!");
self.membersArray = [[PCMSSessionManager sharedSession] memberArr];
// Let's sort the array
self.sortedArray = [self.membersArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(PCMSMember*)a lastName];
NSString *second = [(PCMSMember*)b lastName];
return [first compare:second];
}];
[self.tableView reloadData];
} else {
NSLog(#"boooo!!!!");
}
}];
}
- (NSDictionary *)indexedMembers
{
NSMutableDictionary *indexedContacts = [NSMutableDictionary new];
for (PCMSMember *member in self.sortedArray)
{
NSString *sortString = member.lastName;
NSString *sortLetter = [sortString substringToIndex:1];
/* see if that letter already exists as an index */
BOOL foundKey = NO;
for (NSString *key in [indexedContacts allKeys])
{
if ([key isEqualToString:sortLetter])
{
foundKey = YES;
}
}
NSMutableArray *valueArray;
if (foundKey)
{
valueArray = [((NSArray *)indexedContacts[sortLetter]) mutableCopy];
}
else
{
valueArray = [NSMutableArray new];
}
[valueArray addObject:member];
indexedContacts[sortLetter] = [valueArray copy];
}
return [indexedContacts copy];
}
// Here's my table data
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[[self indexedMembers] allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *indexedContacts = [self indexedMembers];
NSArray *myKeys = [indexedContacts allKeys];
NSString *key = myKeys[section];
return [((NSArray *)[self indexedMembers][key]) count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Configure the cell...
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (self.isPhysician == YES) {
NSString *key = [[self indexedMembers] allKeys][indexPath.section];
PCMSMember *currentMember = ((NSArray *)[self indexedMembers][key])[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", currentMember.firstName, currentMember.lastName];
}
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self indexedMembers] allKeys][section];
}
UPDATE:
This is getting me closer to what I want.
The data is loading, it's being grouped properly and the headers are showing.
But it's not in alphabetical order.
How can I improve this code to show alphabetically?
It's showing in alphabetical order in my console, just not in the app.
The NSMutableDictionary is unordered by definition. It is not the natural choice if you rely on the order of the stored objects. I suggest you to use NSMutableArray instead. To store the tableview data for each section you can use this mini class
#interface MembersWithSameInitial : NSObject
#property (strong) NSString* initial;
#property (strong) NSMutableArray<PCMSMember*>* members;
#end
#implementation MembersWithSameInitial
#end
After you have sorted the members, all the data for the tableview can be produced with this before tableView reload.
NSMutableArray<MembersWithSameInitial*>* groupedMembers = [[NSMutableArray alloc] init];
for (PCMSMember* member in sortedArray) {
NSString* inicial = [member.lastName substringToIndex:1];
MembersWithSameInitial* last = [groupedMembers lastObject];
if (last && [last.initial isEqualToString:inicial]) {
[last.members addObject:member];
} else {
MembersWithSameInitial* newGroup = [[MembersWithSameInitial alloc] init];
newGroup.initial = inicial;
newGroup.members = [[NSMutableArray alloc] initWithObjects:member, nil];
[groupedMembers addObject:newGroup];
}
}
Since the structure of groupedMembers fits to a grouped tableView, the dataSource methods will have trivial implementations. Assuming, that you have stored groupedMembers in a property.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.groupedMembers.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.groupedMembers[section].members.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//...
PCMSMember *currentMember = self.groupedMembers[indexPath.section].members[indexPath.row];
//...
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return groupedMembers[section].initial;
}
Suggestion:
Create two properties
#property NSMutableArray *keys; // for the letters in alphabetical order
#property NSMutableDictionary *indexedContacts; // same as your implementation.
In the method refreshData call the method to create the data source and then reload the table view on the main thread.
Actually you don't need the properties memberArray and sortedArray anymore. The sorted array is passed to the method to create the data source.
- (void)refreshData {
[[PCMSSessionManager sharedSession] refreshPCMSDataWithCompletion:^(BOOL success, NSString *errorMessage, id resultObject) {
if (success) {
NSLog(#"yay!");
self.membersArray = [[PCMSSessionManager sharedSession] memberArr];
// Let's sort the array
NSArray *sortedArray = [self.membersArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(PCMSMember*)a lastName];
NSString *second = [(PCMSMember*)b lastName];
return [first compare:second];
}];
[self indexMembers:sortedArray];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
} else {
NSLog(#"boooo!!!!");
}
}];
}
The method indexMembers initializes the properties keys and indexedContacts and creates the data source.
- (void)indexMembers:(NSArray *)sortedMembers
{
self.keys = [[NSMutableArray alloc] init];
self.indexedContacts = [[NSMutableDictionary alloc] init];
for (PCMSMember *member in sortedMembers)
{
NSString *sortString = member.lastName;
NSString *sortLetter = [sortString substringToIndex:1];
/* see if that letter already exists as an index */
NSArray *keyArray = self.indexedContacts[sortLetter];
NSMutableArray *valueArray;
if (keyArray) {
// array for key exists, use it
valueArray = [keyArray mutableCopy];
} else {
// array for key does not exist, create a new one
valueArray = [NSMutableArray new];
// and add the letter to keys
[self.keys addObject:sortLetter];
}
[valueArray addObject:member];
self.indexedContacts[sortLetter] = [valueArray copy];
}
}
numberOfSectionsInTableView returns the number of keys
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.keys.count;
}
numberOfRowsInSection gets the appropriate array for the given section and returns the number of items.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *letter = self.keys[section];
NSArray *memberArray = self.indexedContacts[letter];
return memberArray.count;
}
In cellForRowAtIndexPath use the method dequeueReusableCellWithIdentifier: forIndexPath: to get always a valid cell. Then like in numberOfRowsInSection get the actual member array and populate the label.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if (self.isPhysician == YES) {
NSString *letter = self.keys[indexPath.section];
NSArray *memberArray = self.indexedContacts[letter];
PCMSMember *currentMember = memberArray[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", currentMember.firstName, currentMember.lastName];
}
return cell;
}
titleForHeaderInSection simply returns the letter for the section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.keys[section];
}
You're calling indexedMembers too much. This is very expensive.
I couldn't test the code, maybe there is a self or something else missing but you get an impression of the workflow.

How to calculate dynamic no of rows in each section

I am developing iPhone app and i got stuck at one point need your help,
I have tableview with dynamic sections and dynamic no of rows in each section.
Here is my json data format: http://pastebin.com/jmsq1pxu
I have fetched all this data in my array,
now i have calculated number of sections in tableview based on SpecGroupLabel key:
I found section count as 10
General,
Body,
Display,
Memory,
Camera,
Connectivity,
OS,
Processor,
Battery,
Sound
Now in each section i want to calculate no of rows.
Here in this case 1st section is General 2nd is Body 3rd is Display and so on upto 10th section Sound i want to calculate no of rows in each section ?
and finally how should i display different section and it's row in cellForRowAtIndexPath ?
Please help and thanks in advance.
I'll explain in detail
Suppose you have the following json
{
data:[
{
label:Fruit,
name: Orange,
},
{
label:Month,
name: June,
},
{
label:Color,
name: Blue,
},
{
label:Color,
name: Red,
},
{
label:Fruit,
name: Apple,
},
{
label:Color,
name: Pink,
},
{
label:Fruit,
name: Mango,
},
{
label:Month,
name: May,
},
{
label:Color,
name: White,
},
]
}
And you want your table to look like
Fruit
Orange
Apple
Mango
Month
June
May
Color
Blue
Red
Pink
White
NSMutableDictionary *dict;
- (void)viewDidLoad
{
[super viewDidLoad];
dict = [[NSMutableDictionary alloc] init];
NSArray *jsonArray ;// this is your data json array
for (int i = 0; i < jsonArray.count; i++) {
NSDictionary *dataDict = [jsonArray objectAtIndex:i];
NSString *getLabel = [dataDict objectForKey:#"label"];
if([dict objectForKey:getLabel] == NULL){
//this label is not present in your dict, so that means its a new section.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
[newArray addObject:[dataDict objectForKey:#"name"]];
[dict setObject:newArray forKey:getLabel];
}else{
// already added to the dictionary
NSMutableArray *getArray = [dict objectForKey:getLabel];
[getArray addObject:[dataDict objectForKey:#"name"]];
}
}
// Do any additional setup after loading the view, typically from a nib.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return dict.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *getArray = [dict.allValues objectAtIndex:section];
return getArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection: (NSInteger)section{
return 40.0;
}
-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)];
UILabel *sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)];
sectionLabel.text = [dict.allKeys objectAtIndex:section];
[view addSubview:sectionLabel];
return view;
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSArray *getArray = [dict.allValues objectAtIndex:indexPath.section];
cell.textLabel.text = [getArray objectAtIndex:indexPath.row];
}
the number of the groups:
NSInteger _numberOfGroups = [[_array valueForKeyPath:#"#distinctUnionOfObjects.SpecGroupLabel"] count];
the number of the items in a particular group (e.g. "General"):
NSInteger _numberOfItemsInAGroup = [[_array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
return [[evaluatedObject valueForKey:#"SpecGroupLabel"] isEqualToString:#"General"]; // or Body, Display, Memory, Camera, Connectivity, etc...
}]] count];
NOTE: you can read more about KVC here and predicates here.
You need to create an array of arrays. Each array will represent a section. Within each array add your data for an individual row.
To get number of rows in a section:
NSInteger rows = array[section].count
In cellForRowAtIndexPath use the indexpath
CustomObject *object = [array[indexPath.section] objectAtIndex:indexPath.row]

How to show Data in UITableView ios

Developing a iPAD app, where I'm trying to populate table, This is how i'm doing:
In view did load, I'm creating two dictionary object and adding object as Pdf and Excel.
- (void)viewDidLoad
{
[super viewDidLoad];
arrDocuments = [[NSMutableArray alloc] init];
NSArray *arr1 = [NSArray arrayWithObjects:#"PDF", nil];
NSDictionary *pdf = [NSDictionary dictionaryWithObjects:arr1 forKeys:nil];
NSArray *arr2 = [NSArray arrayWithObjects:#"Excel", nil];
NSDictionary *excel = [NSDictionary dictionaryWithObjects:arr2 forKeys:nil];
[arrDocuments addObject:pdf];
[arrDocuments addObject:excel];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrDocuments count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//return [arrReceipes count];
NSDictionary *dictionary = [arrDocuments objectAtIndex:section];
NSArray *array = [dictionary objectForKey:[self.sortedKeys objectAtIndex:section]];
return [array count];
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableView *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell ==nil) {
cell = [[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:MyIdentifier];
}
return cell;
}
With this implementation I'm not able to see table view.Its going to main method and showing me SIGABRT message.Where I'm going wrong??
While creating NSDictionary, you have passed nil in place of keys array,
NSDictionary *pdf = [NSDictionary dictionaryWithObjects:arr1 forKeys:nil];
You should give proper objects and keys to the dictionary. This method expects objects and keys to be given in an array as you can see in its method signature.
+ (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys

Accessing NSMutableArray Objects For Using On TableView

I started develop an app which is using WCF service with JSON data. I got the data from WCF service but I didn't use it as I want.
here is the JSON data:
{"MenuDoldurAndroidResult":[
{"menu_description":"Turkish Pizza","menu_title":"L Pizza","menu_price":"26 TL"},{"menu_description":"Italiano Pizza","menu_title":"L Pizza","menu_price":"27 TL"},{"menu_description":"Extravaganza","menu_title":"L Pizza","menu_price":"29 TL"},{"menu_description":"Pepporoni Pizza","menu_title":"L Pizza","menu_price":"28 TL"},{"menu_description":"Turkish Pizza","menu_title":"S Pizza","menu_price":"12 TL"},{"menu_description":"Italiano Pizza","menu_title":"S Pizza","menu_price":"13 TL"},{"menu_description":"Extravaganza","menu_title":"S Pizza","menu_price":"15 TL"},{"menu_description":"Pepporoni Pizza","menu_title":"S Pizza","menu_price":"14 TL"}
]}
What I want:
If there are 2 title here, there must be 2 section in table view. Every item must be in their section.
Like this:
-L Pizzas
Turkish Pizza 26 TL
Italiano Pizza 27 TL
Extravaganza Pizza 29 TL
Pepperoni Pizza 28 TL
-S Pizzas
Turkish Pizza 12 TL
Italiano Pizza 13 TL
Extravaganza Pizza 15 TL
Pepperoni Pizza 14 TL
How can I access this item and display like this ?
- (void)viewDidLoad
{
[super viewDidLoad];
//I posted request to service here. I didn't write these parts of code.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *array= [json objectForKey:#"MenuDoldurAndroidResult"];
menu = [[NSMutableArray alloc] initWithCapacity:3];
NSString *descriptionTemp;
NSString *titleTemp;
NSString *priceTemp;
for(int i=0; i< array.count; i++)
{
NSDictionary *menuList= [array objectAtIndex:i];
titleTemp = [menuList objectForKey:#"menu_title"];
descriptionTemp = [menuList objectForKey:#"menu_description"];
priceTemp = [menuList objectForKey:#"menu_price"];
[menu addObject:[NSArray arrayWithObjects:titleTemp,descriptionTemp,priceTemp,nil]];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
-(NSString *)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section{
if (section==0) {
return #"L Pizzas";
}
else{
return #"S Pizzas";
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
cell.textLabel.text = [menu objectAtIndex: indexPath.row];
return cell;
}
If your content is static you can try using the answer by Sunny. But if is dynamic it's better to store the data in a different way. Obviously L pizza and S pizza seems to be a category and the rest are like category items.
You need to make a collection of the categories. Demo Project Source Code
- (void)viewDidLoad
{
[super viewDidLoad];
//I posted request to service here. I didn't write these parts of code.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *allPizzas = [json[#"MenuDoldurAndroidResult"] mutableCopy];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"menu_price"
ascending:YES
selector:#selector(compare:)];
[allPizzas sortUsingDescriptors:#[sortDescriptor]];
NSMutableArray *pizzaCategories = [#[]mutableCopy];
//Find unique categories in all the pizzas
NSSet* categories = [NSSet setWithArray: [allPizzas valueForKey:#"menu_title"]];
//Enumerate to form a new reformatted category array
for (NSString *categoryTitle in categories)
{
//Predicate is used to find the items that come under current category
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"menu_title == %#",categoryTitle];
NSArray *categoryItems = [allPizzas filteredArrayUsingPredicate:predicate];
//New dictionary with name of category and category items are formed
NSDictionary *categoryDict = #{#"menu_title":categoryTitle,#"pizzas":categoryItems};
[pizzaCategories addObject:categoryDict];
}
//Assign the new formatted category array to the instance variable for holding categories.
self.categories = pizzaCategories;
}
Modify the datasource of tableView for the new structure
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//The count of categories will give number of sections
NSUInteger sections = [self.categories count];
return sections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//The number of items in a category is calculated
NSDictionary *category = self.categories[section];
return [category[#"pizzas"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//Title for the category
NSDictionary *category = self.categories[section];
return category[#"menu_title"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
NSDictionary *category = self.categories[indexPath.section];
NSArray *categoryItems = category[#"pizzas"];
NSDictionary *categoryItem = categoryItems[indexPath.row];
cell.textLabel.text = categoryItem[#"menu_description"];
cell.detailTextLabel.text = categoryItem[#"menu_price"];
return cell;
}
You can also use the free Sensible TableView framework to fetch the data from the web service and automatically display it in your table view.

Resources