Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger numberOfRowsPerSection = 0;
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] > 50) {
numberOfRowsPerSection ++;
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] == 73) {
numberOfRowsPerSection ++;
}
}
}
return numberOfRowsPerSection;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (!cell) {
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
}
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
if ([p valueInDollars] > 50 && indexPath.section == 0) {
[[cell textLabel] setText:[p description]];
}else if(indexPath.section == 1){
[[cell textLabel] setText:[p description]];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
I want to display in one section results > 50 and the other section the rest of the result but I don't know how to do it. I am getting duplicate results in each section.
Thanks
Your code doesn't reflect what you're describing ( > 50 and == 73 are kind of intersecting):
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] > 50) {
...
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] == 73) {
...
}
}
}
And this line is incorrect too:
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
because the indexPath.row will go with an indexPath.section (it means the row is relative to the section, not to the whole table). This is main cause of your problem having the same results for both sections.
Anyway, my suggestion for you is to perform a preprocessing step (maybe in viewDidLoad or somewhere else) to split your array into 2 arrays (one for each section) instead of using only one array for both sections.
If you are using a NSFetchedResultsController you can use the sectionNameKeyPath: argument to specify a "group-by" parameter. In your case you might just create a simple 0/1 property to your objects in the array.
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_managedObjectContext
sectionNameKeyPath:#"threshold"
cacheName:#"Root"];
Related
I'm trying to create a second section which is where section.indexPath = 0. This section is objects which is generated from distance between two locations which is done in the didUpdateToLocation. When trying to populate the tableview with the objects from the array it shows:
index 0 beyond bounds for empty array'
How can i show the nearStoresArray in the tableview without getting the empty array error.
Here is the cellForRowAtIndexPath. Here it gives an error and say that nearStoresArray is empty. I guess thats because the tableview is showing before the didUpdateToLocation.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0) {
indexNo = [nearStoresArray objectAtIndex:indexPath.row];
NSLog(#"%d", [nearStoresArray count]);
} else if (indexPath.section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
indexNo = [filteredArray objectAtIndex:indexPath.row];
} else {
indexNo = [storesArray objectAtIndex:indexPath.row];
}
}
cell.textLabel.text = [indexNo valueForKey:#"name"];
return cell;
}
Here is the didUpdateToLocation method. This method creates the nearStoresArray, which works fine.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[locationManager stopUpdatingLocation];
locationManager = nil;
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
for (int i = 0; i < [storesArray count]; i++) {
CLLocationDegrees latitude = [[[storesArray objectAtIndex:i] valueForKey:#"lat"] doubleValue];
CLLocationDegrees longitude = [[[storesArray objectAtIndex:i] valueForKey:#"long"] doubleValue];
CLLocation *checkPosition = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
CLLocationDistance distance = [checkPosition distanceFromLocation:currentLocation];
float distanceInKm = distance / 1000;
if (distanceInKm < 5) {
[nearStoresArray removeAllObjects];
[nearStoresArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
[[storesArray objectAtIndex:i] valueForKey:#"id"], #"id",
[[storesArray objectAtIndex:i] valueForKey:#"name"], #"name",
[[storesArray objectAtIndex:i] valueForKey:#"lat"], #"lat",
[[storesArray objectAtIndex:i] valueForKey:#"long"], #"long",
[[storesArray objectAtIndex:i] valueForKey:#"address"], #"address",
[[storesArray objectAtIndex:i] valueForKey:#"zip"], #"zip"
, nil]];
NSLog(#"%#", nearStoresArray);
}
[self.tableView reloadData];
}
}
}
numberOfRows Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section==0) {
return [nearStoresArray count];
} else if (section==1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
} else {
return [storesArray count];
}
} else {
return 0;
}
}
You can directly Access Section Like
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [nearStoresArray count];
}
else if (section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
}
else {
return [storesArray count];
}
}
}
I believe you need to update numberOfRowsInSection method, like below -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [nearStoresArray count];
}
else if (section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
}
else {
return [storesArray count];
}
}
else {
return 0;
}
}
My project is based on parsing xml data and adding it to array and display in respectives views,now my problem is am parsing xml and adding those objects it to nsmutablearray as shown below:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
samplearray = [[NSMutableArray alloc]init];
xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
for (int i =0; i<[rssOutputData count]; i++) {
NewsList *log = [rssOutputData objectAtIndex:i];
feedid = log.id;
NSLog(#"%d",feedid);
Invit = log.newsletterdet;
NSLog(#"%#",Invit);
[samplearray addObject:log];
NSLog(#"Count Final %d",[self.samplearray count]);
}
[[self navigationController] tabBarItem].badgeValue = mycount2;
NSLog(#"%#",mycount2);
[tblView reloadData];
[connection release];
}
The Above prints Count Value as 2014-04-04 15:21:10.009 cftsversion1[3087:70b] Count Final 1
But when I call those Count in tableview methods, it prints 0 so I cannot load datas in tableview Here is the code I tried for tableview methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return [samplearray count];Prints 0 here
NSLog(#"Count %d",[samplearray count]); Prints 0 here
if (section == 1)
return 1;
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"eventCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}
if (indexPath.section == 0)
{
NewsList *msglist = [samplearray objectAtIndex:indexPath.row];
cell.textLabel.text = msglist.newsletterdet;
NSLog(#"%#",msglist.newsletterdet);
NSInteger stat = msglist.readflag;
if ([[SingleTonClass sinlgeTon].colorArray2 containsObject:[NSString stringWithFormat:#"%d",indexPath.row]] || stat == 1) {
cell.textLabel.textColor = [UIColor redColor];
}
else{
cell.textLabel.textColor = [UIColor greenColor];
}
cell.backgroundColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 1)
{
UIButton *viewmoreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
viewmoreButton.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
[viewmoreButton setTitle:#"View More" forState:UIControlStateNormal];
[cell addSubview:viewmoreButton];
[viewmoreButton addTarget:self
action:#selector(viewMore:)
forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:viewmoreButton];
}
return cell;
}
When run the above tableview code section 0 is not at all loading because array count prints 0 only section 1 is loading please help me how to solve this issue Thanks in advance
Intialize sampleArray in ViewDidLoad
samplearray = [[NSMutableArray alloc]init]
Make sure [tblView reloadData] is working properly.Initialy table will be loaded before completion of connectionDidFinishLoading, so count will be 0. Only in reload the count increments.
I have doubt you are printing value in wrong way. Try to print it correctly first and update us:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
NSLog(#"Count %d",[samplearray count]);\\ Prints 0 here
return [samplearray count];\\Prints 0 here
}
else if (section == 1)
{
return 1;
}
return 0;
}
and declare your NSMutableArray in .h file like:
#property (nonatomic, strong) NSMutableArray *samplearray;
I have a UITableView with sections that "collapse" when you tap the section header. When the section collapses, it really just removes the rows from the section. When I try to reorder a cell from another section below the collapsed section into the collapsed section, the app crashes. I get this error:
*** Assertion failure in -[_UITableViewUpdateSupport _setupAnimationForReorderingRow], /SourceCache/UIKit/UIKit-2380.17/UITableViewSupport.m:847
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempt to create two animations for cell'
What's strange is that it works fine if I'm moving the cell into a collapsed section from above the collapsed section. It only crashes if I move it from below the collapsed section.
Here's my code:
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
if ([proposedDestinationIndexPath section] == 0 && [[JRBTaskStore sharedStore] isTodayCollapsed])
[self hideShowToday];
else if ([proposedDestinationIndexPath section] == 1 && [[JRBTaskStore sharedStore] isTomorrowCollapsed])
[self hideShowTomorrow];
else if ([proposedDestinationIndexPath section] == 2 && [[JRBTaskStore sharedStore] isUpcomingCollapsed])
[self hideShowUpcoming];
else if ([proposedDestinationIndexPath section] == 3 && [[JRBTaskStore sharedStore] isSomedayCollapsed])
[self hideShowSomeday];
return proposedDestinationIndexPath;
}
-(void)hideShowToday
{
[self setDayType: TaskDayTypeToday];
[self hideShowSection: 0 rows: numberOfRowsInToday array: [[JRBTaskStore sharedStore] todayTasks]];
}
-(void)hideShowTomorrow
{
[self setDayType: TaskDayTypeTomorrow];
[self hideShowSection: 1 rows: numberOfRowsInTomorrow array: [[JRBTaskStore sharedStore] tomorrowTasks]];
}
-(void)hideShowUpcoming
{
[self setDayType: TaskDayTypeUpcoming];
[self hideShowSection: 2 rows: numberOfRowsInUpcoming array: [[JRBTaskStore sharedStore] upcomingTasks]];
}
-(void)hideShowSomeday
{
[self setDayType: TaskDayTypeSomeday];
[self hideShowSection: 3 rows: numberOfRowsInSomeday array: [[JRBTaskStore sharedStore] somedayTasks]];
}
-(void)hideShowSection:(int)section rows:(int)numRows array:(NSArray *)array
{
if ([array count] > 0 && [[self tableView] numberOfRowsInSection: section] == 0) {
// Uncollapse the section
// Create an array of index paths
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
int i = [array count];
for (int x = 0; x < i; x++) {
NSIndexPath *ip = [NSIndexPath indexPathForRow: x inSection: section];
[indexPaths addObject: ip];
}
if (dayType == TaskDayTypeToday) {
numberOfRowsInToday = [array count];
[[JRBTaskStore sharedStore] setIsTodayCollapsed: NO];
}
if (dayType == TaskDayTypeTomorrow) {
numberOfRowsInTomorrow = [array count];
[[JRBTaskStore sharedStore] setIsTomorrowCollapsed: NO];
}
if (dayType == TaskDayTypeUpcoming) {
numberOfRowsInUpcoming = [array count];
[[JRBTaskStore sharedStore] setIsUpcomingCollapsed: NO];
}
if (dayType == TaskDayTypeSomeday) {
numberOfRowsInSomeday = [array count];
[[JRBTaskStore sharedStore] setIsSomedayCollapsed: NO];
}
// Getting the error here
[[self tableView] insertRowsAtIndexPaths: indexPaths withRowAnimation: UITableViewRowAnimationAutomatic];
}
else if ([array count] > 0 && [[self tableView] numberOfRowsInSection: section] > 0) {
// Collapse the section
// Find the index paths of the rows and delete them
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
int i = [[self tableView] numberOfRowsInSection: section];
for (int x = 0; x < i; x++) {
NSIndexPath *ip = [NSIndexPath indexPathForRow: x inSection: section];
[indexPaths addObject: ip];
}
if (dayType == TaskDayTypeToday) {
numberOfRowsInToday = 0;
[[JRBTaskStore sharedStore] setIsTodayCollapsed: YES];
}
if (dayType == TaskDayTypeTomorrow) {
numberOfRowsInTomorrow = 0;
[[JRBTaskStore sharedStore] setIsTomorrowCollapsed: YES];
}
if (dayType == TaskDayTypeUpcoming) {
numberOfRowsInUpcoming = 0;
[[JRBTaskStore sharedStore] setIsUpcomingCollapsed: YES];
}
if (dayType == TaskDayTypeSomeday) {
numberOfRowsInSomeday = 0;
[[JRBTaskStore sharedStore] setIsSomedayCollapsed: YES];
}
[[self tableView] deleteRowsAtIndexPaths: indexPaths withRowAnimation: UITableViewRowAnimationTop];
}
else if ([array count] == 0) {
// There's nothing in the section
}
}
I'm willing to change a specific header view of my UITableView when I click a row.
I've read all posts about it yet. I tried "reloadData", "setNeedDisplay", "reloadSections:withRowAnimation:", and several others ideas... there is nothing to do. My header view either doesn't update or it does weird things like updating only when I move the table view (which is not what I'm willing to achieve).
My code looks like this for now (regarding the UITableView delegates methods):
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
if(tableView==_storeTableView){
return [_storeDataArray count];
} else {
return 1;
}
}
-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
if(tableView==_storeTableView){
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:section];
if (!headerModel.headerView) {
NSString *shelfName = headerModel.shelf;
headerModel.headerView = [[[HouraStoreHeaderView alloc] initWithFrame:CGRectMake(0.0, 0.0, _storeTableView.bounds.size.width, 80) title:shelfName section:section subheaderNumber:([headerModel.openedSubHeaders count]-1) delegate:self] autorelease];
}
return headerModel.headerView;
} else {
return nil;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView==_storeTableView){
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:section];
NSDictionary *myDict = _storeDataDict;
for (NSInteger i = 0; i < [headerModel.openedSubHeaders count]; i++) {
myDict = [myDict objectForKey:[headerModel.openedSubHeaders objectAtIndex:i]];
}
NSInteger numberOfRowsInSection = [[myDict allKeys] count];
return headerModel.open ? numberOfRowsInSection : 0;
} else if(tableView==_searchTableView){
return [_resultArray count];
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if(tableView==_storeTableView){
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:indexPath.section];
NSDictionary *myDict = _storeDataDict;
for (NSInteger i = 0; i < [headerModel.openedSubHeaders count]; i++) {
myDict = [myDict objectForKey:[headerModel.openedSubHeaders objectAtIndex:i]];
}
cell.accessoryView=[[[HouraStoreCellView alloc] initWithFrame:CGRectMake(0.0, 0.0, _storeTableView.bounds.size.width, 50) title:[[myDict allKeys] objectAtIndex:indexPath.row]] autorelease];
return cell;
} else if (tableView==_searchTableView) {
cell.textLabel.text = [_resultArray objectAtIndex:indexPath.row];
return cell;
} else {
return cell;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:section];
NSInteger height = 59.0 + ([headerModel.openedSubHeaders count]-1)*41.0;
return height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(tableView==_storeTableView){
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:indexPath.section];
NSDictionary *myDict = _storeDataDict;
for (NSInteger i = 0; i < [headerModel.openedSubHeaders count]; i++) {
myDict = [myDict objectForKey:[headerModel.openedSubHeaders objectAtIndex:i]];
}
if ([[myDict objectForKey:[[myDict allKeys] objectAtIndex:indexPath.row]] isKindOfClass:[NSDictionary class]]) {
[self cellOpened:indexPath];
} else {
[_activityIndicatorView startAnimating];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_listProductsFoundedFinished:)
name:HouraSearchProductsDone
object:nil];
NSString *searchString = [[myDict allKeys] objectAtIndex:indexPath.row];
searchString = [searchString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\u0022"];
[_singleton.util beginSearchProducts:searchString context:#"2"];
}
} else if(tableView==_searchTableView){
_searchBar.text = [_resultArray objectAtIndex:indexPath.row];
[_searchBar resignFirstResponder];
[_activityIndicatorView startAnimating];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_listProductsFoundedFinished:)
name:HouraSearchProductsDone
object:nil];
[_singleton.util beginSearchProducts:_searchBar.text context:#"2"];
}
}
-(void)headerView:(HouraStoreHeaderView*)headerView headerOpened:(NSInteger)headerOpened {
if (self.openSectionIndex!=NSNotFound) {
[self closeAllHeaders];
}
//[self closeAllHeaders];
HouraStoreHeaderModel *headerModel =nil;
headerModel = [self.headerInfoArray objectAtIndex:headerOpened];
headerModel.open = YES;
headerModel.headerView.disclosureButton.selected = YES;
NSDictionary *myDict = _storeDataDict;
for (NSInteger i = 0; i < [headerModel.openedSubHeaders count]; i++) {
myDict = [myDict objectForKey:[headerModel.openedSubHeaders objectAtIndex:i]];
}
NSInteger countOfRowsToInsert = [[myDict allKeys] count];
NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
[indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:headerOpened]];
}
NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
NSInteger previousOpenSectionIndex = self.openSectionIndex;
if (previousOpenSectionIndex != NSNotFound) {
HouraStoreHeaderModel *previousHeaderModel = [self.headerInfoArray objectAtIndex:previousOpenSectionIndex];
previousHeaderModel.open = NO;
previousHeaderModel.headerView.disclosureButton.selected = NO;
[previousHeaderModel.headerView toggleOpenWithUserAction:NO];
NSInteger countOfRowsToDelete = [[[_storeDataDict objectForKey:previousHeaderModel.shelf ] allKeys] count];
for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
[indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex]];
}
}
UITableViewRowAnimation insertAnimation;
UITableViewRowAnimation deleteAnimation;
if (previousOpenSectionIndex == NSNotFound || headerOpened < previousOpenSectionIndex) {
insertAnimation = UITableViewRowAnimationTop;
deleteAnimation = UITableViewRowAnimationBottom;
} else {
insertAnimation = UITableViewRowAnimationBottom;
deleteAnimation = UITableViewRowAnimationTop;
}
[_storeTableView beginUpdates];
[_storeTableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:deleteAnimation];
[_storeTableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
[_storeTableView endUpdates];
self.openSectionIndex = headerOpened;
}
-(void)headerView:(HouraStoreHeaderView*)headerView headerClosed:(NSInteger)headerClosed {
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:headerClosed];
headerModel.open = NO;
headerModel.headerView.disclosureButton.selected = NO;
[headerModel cleanOpenedSubHeaders];
[self.headerInfoArray replaceObjectAtIndex:headerClosed withObject:headerModel];
NSInteger countOfRowsToDelete = [_storeTableView numberOfRowsInSection:headerClosed];
if (countOfRowsToDelete > 0) {
NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
[indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:headerClosed]];
}
[_storeTableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
}
self.openSectionIndex = NSNotFound;
}
-(void)cellOpened:(NSIndexPath*)indexPath {
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:indexPath.section];
[self headerView:headerModel.headerView headerClosed:indexPath.section];
[headerModel addOpenedSubHeaders:[[[_storeDataDict objectForKey:headerModel.shelf] allKeys] objectAtIndex:indexPath.row]];
[self.headerInfoArray replaceObjectAtIndex:indexPath.section withObject:headerModel];
headerModel = [self.headerInfoArray objectAtIndex:indexPath.section];
[self headerView:headerModel.headerView headerOpened:indexPath.section];
}
-(void)closeAllHeaders {
for (NSInteger i = 0; i < [self.headerInfoArray count]; i++) {
HouraStoreHeaderModel *headerModel = [self.headerInfoArray objectAtIndex:i];
[self headerView:headerModel.headerView headerClosed:i];
}
}
What I'd like to do is, when I click a row, the section header update so it contains a new button with the row text. Then I dismiss the row and reload new datas in the section rows. I managed to handle the rows perfectly. But I can't find a way to get this header view updated.
Thx for any idea.
You just change it directly. I created an instance variable in the header file for a label that I will put in the header's view I'll create:
#interface MainViewController : UITableViewController {
// creating my datasource array instance variable
NSArray *_items;
// this is the label I will add to the header view when I create it
UILabel *_headerLabel;
}
#end
And in my tableView when they select a row I call a function that simply changes the text on the label:
#implementation MainViewController
- (id)init {
self = [super initWithStyle:UITableViewStyleGrouped];
/ filling my datasource with test strings
_items = #[#"one", #"two"];
return self;
}
- (void)changeHeaderLabel:(NSString *)newLabel {
// when this function gets called and is passed a string, I will simply
// set the text on the label to the new string and viola!
_headerLabel.text = newLabel;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// this table will only have a single section for demo purposes
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// return the count of my datasource array
return _items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// attempt to create a cell by reusing one with a given identifier
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
// if I wasn't able to reuse one
if (cell == nil) {
// create one from scratch with that identifier
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
// now simply set the text on the cell from my data source array of strings
cell.textLabel.text = _items[indexPath.row];
// and return the cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// deselect the row so the cell automatically fades out after selection
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// here you could do one of two things, either get a reference to the cell itself,
// and then get the value stored in it's textLabel
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *newHeaderTitleString = selectedCell.textLabel.text;
// OR you can get it right from your datasource
NSString *newHeaderTitleString = _items[indexPath.row];
// then just call the above function with the string as the single param
[self changeHeaderLabel:newHeaderTitleString];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// here I just create a view that will span the whole frame and is an arbitrary height
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
// set the background color to clear
headerView.backgroundColor = [UIColor clearColor];
// then I initialize my instance variable with a frame that's centered in the view
// for aesthetic purposes
_headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 10, 80)];
// then I set the text color, add an autoresizing mask so if the view rotates
// it still remains centered properly, set the text to some starting value,
// and add it to the headerView I previously created
_headerLabel.textColor = [UIColor darkGrayColor];
_headerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_headerLabel.text = #"Before";
[headerView addSubview:_headerLabel];
// then I return the headerView
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
// return an arbitrary height here for testing
return 80;
}
That results in the following:
If you have any questions let me know! This is just a quick example to demonstrate it, but you may want to customize the view in a different way altogether. This should at least solve your problem and give you a starting point to work from.
Have you tried reloadRowsAtIndexPaths:withRowAnimation: where you set the row property of the NSIndexPath passed in as NSNotFound? So reloading just the header of section 3, for instance would look like
NSIndexPath * headerIndexPath = [NSIndexPath indexPathForRow: NSNotFound section:3];
[self.tableView reloadRowsAtIndexPaths:#[headerIndexPath] withRowAnimation: UITableViewRowAnimationAutomatic];
I guarantee nothing, but I'm pretty sure it used to work before, because I used it a couple of times.
But even if it works, it's still a hack that might get broken by Apple any time.
edit
Ok, never mind. I tried this with iOS 7 in Xcode 5 and for some reason, even with NSNotFound as the row number, it still reloads the whole sections (with all its cells). So this does not work any more, damn.
I have a problem on uitableview,
I have taken 3 sections in grouped table,
Inserted data for each section by using indexPath.section all is well but 3rd section is filled with both 1st and 2nd section data,
How to remove that data and how to fill my own data means separate data?
Code is:-
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return #"Product Details";
}
if (section == 1) {
return #"Ingredients";
}
if (section == 2) {
return #"My Allergies";
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return 150;
}
if (indexPath.section == 1) {
return 100;
}
if (indexPath.section==2) {
return 45;
}
return 0;
}
- (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] autorelease];
}
NSMutableString *redStr1 =[[NSMutableString alloc] initWithString:#"No" ];
NSMutableString *yellowStr1 =[[NSMutableString alloc] initWithString:#"No" ];
NSMutableString *greenStr1 =[[NSMutableString alloc] initWithString:#"No" ];
int a = [appDelegate.reIndex intValue];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [appDelegate.ProductArray objectAtIndex:a];
// NSMutableString *str = [aDict1 objectForKey:#"IngredientInfo"];
NSMutableArray *array =[aDict1 objectForKey:#"IngredientInfo1"];
NSMutableString *nameStr = [[NSMutableString alloc] init];
NSMutableString *nameClr = [[NSMutableString alloc] init];
for (int s=0; s<[array count]; s++) {
NSDictionary *nameDict = [array objectAtIndex:s];
[nameStr appendString:[nameDict objectForKey:#"Name"]];
nameClr = [nameDict objectForKey:#"HalaStatus"];
if ([nameClr isEqualToString:#"Red"]) {
[redStr1 setString:#"Yes"];
}
if ([nameClr isEqualToString:#"Yellow"]) {
[yellowStr1 setString:#"Yes"];
}
if ([nameClr isEqualToString:#"Green"]) {
[greenStr1 setString:#"Yes"];
}
if (s == [array count]-1) {
[nameStr appendFormat:#"."];
}
else {
[nameStr appendFormat:#","];
}
}
if (indexPath.section == 0)
{
cell.userInteractionEnabled =NO;
imgview1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"images (1).jpg"] ];
[imgview1 setFrame:CGRectMake(12, 2, 100, 145)];
[cell addSubview:imgview1];
[imgview1 release];
imgview = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 50, 45)];
[cell addSubview:imgview];
if ([redStr1 isEqualToString:#"Yes"]) {
[imgview setImage:[UIImage imageNamed:#"Red.png"]];
}
if ([redStr1 isEqualToString:#"No"] && [yellowStr1 isEqualToString:#"Yes"] ) {
[imgview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([redStr1 isEqualToString:#"No"] && [yellowStr1 isEqualToString:#"No"] && [greenStr1 isEqualToString:#"Yes"]) {
[imgview setImage:[UIImage imageNamed:#"Green.png"]];
}
}
if (indexPath.section == 1) {
UITextView *textview1;
textview1 =[[UITextView alloc]initWithFrame:CGRectMake(12, 2, 294, 96)];
textview1.text = nameStr;
textview1.editable =NO;
[textview1 setFont:[UIFont systemFontOfSize:15]];
[cell addSubview:textview1];
}
if (indexPath.section == 2) {
cell.textLabel.text = [arr objectAtIndex:indexPath.row];
}
return cell;
}
if you have an array and access this in cellForRowAtIndexPath: with indexPath.row you will get for all sections the same lets say three elements.
What you have to do is an array inside an array:
Level 1 Section 1
Level 2 Row 1
Level 2 Row 2
Level 2 Row 3
Level 1 Section 2
Level 2 Row 1
Level 2 Row 2
Level 1 Section 3
Level 2 Row 1
Level 2 Row 2
Level 2 Row 3