trouble with section headers in UITableView - iphone

im having a problem with setting my section headers in a uitableview, its probably something really simple i just cant work it out.
instead of displaying different headers for different sections it displays the same header for each section
help me please :)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
WorldCupAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
return [appDelegate.matchFixtures count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
WorldCupAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
Fixtures *fixtures = [appDelegate.matchFixtures objectAtIndex:section];
return fixtures.matchDate;
}

Your original code looks okay. I'm betting that appDelegate.matchFixtures doesn't contain the data you think it does. Modify your code to look like this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
WorldCupAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSLog(#"appDelegate.matchFixtures.count = %i", appDelegate.matchFixtures.count);
return [appDelegate.matchFixtures count];
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
WorldCupAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
Fixtures *fixtures = [appDelegate.matchFixtures objectAtIndex:section];
NSLog(#"For section %i, fixtures.matchDate = %#", section, fixtures.matchDate);
return fixtures.matchDate;
}
And look at the log output in the debug console.

Try like this
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
NSString *title = nil;
// Return a title or nil as appropriate for the section.
switch (section) {
case 0:
title = [[appDelegate.matchFixtures objectAtIndex:section]matchDate];
break;
case 1:
title = [[appDelegate.matchFixtures objectAtIndex:section]matchDate];
break;
case 2:
title = [[appDelegate.matchFixtures objectAtIndex:section]matchDate];
break;
default:
break;
}
return title;
}
Edit
Set the date properly with retain in the delegate class.Even i had some problems similar when storing values in delegates.
- (void)setCurrentDates:(NSString *)value {
[value retain]; // <- Retain new value
[date release]; // <- Release old value;
date = value;
}
All the best.

Related

Why my tableView always work with empty cell?

I made a simple code for tableView to display some player data; however, I got the empty table all the time.
This is a table with data fetched from the site.
I want to show the table with player number(as section) and player name(as row).
But after I run the program, it comes out the empty cells and seems no fetching attempt.
Can anyone tell me what's wrong with my code? Thanks a lot.
#import "playerName.h"
#interface playerName ()
#end
#implementation playerName
#synthesize players = _players;
#synthesize sectionInRtf = _sectionInRtf;
- (NSMutableDictionary *)getPlayerFormRtf
{
if (!_players) {
NSURL *url = [NSURL URLWithString:#"file_on_site"];
_players = [NSMutableDictionary dictionaryWithContentsOfURL:url];
}
return _players;
}
- (NSArray *)getSections
{
if (!_sectionInRtf) {
_sectionInRtf = [self.players allKeys];
}
return _sectionInRtf;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Players";
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.sectionInRtf.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *namesInSection = [self.players objectForKey:[self.sectionInRtf objectAtIndex:section]];
return namesInSection.count;
}
//Additional Method
- (NSString *)name:(NSIndexPath *)indexPath
{
NSArray *nameInSection2 = [self.players objectForKey:[self.sectionInRtf objectAtIndex:indexPath.section]];
return [nameInSection2 objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"players";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text = [self name:indexPath];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#end
This looks like you are trying to override the accessor methods but you are not using the correct naming. I make this assumption since you never actually call getPlayerFormRtf.
The code should work (though not well) with two simple modifications.
- (NSMutableDictionary *)players
{
if (!_players) {
NSURL *url = [NSURL URLWithString:#"file_on_site"];
_players = [NSMutableDictionary dictionaryWithContentsOfURL:url];
}
return _players;
}
- (NSArray *)sectionInRtf
{
if (!_sectionInRtf) {
_sectionInRtf = [self.players allKeys];
}
return _sectionInRtf;
}
PLEASE note that this is an extremely bad idea, referring to the synchronous loading of a url, since your placeholder url string seems to imply a network access url. This risks blocking the main thread long enough for the application to be killed.

UITableView Splitting contents into Sections

I have a UITableView for which I have listed the code below.
How do I section these objects out such as the following shown below?
Math
Algebra
Geometry
Calculus
Science
Integrated 1
Integrated 2
Here is the code:
- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects:#"Math",#"Science",#"English",#"Social Studies",#"Spanish",#"German",#"French",#"Biology",nil];
self.listData = array;
[array release];
[super viewDidLoad];
}
You have to use sectioned table view, that is the best way to achieve this. You can refer following tutorial for the same - http://www.xcode-tutorials.com/uitableview-–-3-sectioned-table-view/
In your UITableViewDataSource of UITableView object;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return array.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [array objectAtIndex:section];
}
will do the 'sectioning' part for your case.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [yourarray count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [yourarray objectAtIndex:section];
}

display the right section of tableview

I have a table view and I'm toggling its dataDource with two UIButtons (like tabs).
- (IBAction)dataToggler:(id)sender {
int buttonTag = ((UIButton*)sender).tag;
if(_firstTab.selected && buttonTag != 1){
AppDelegate *myAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
myAppDelegate.isFeatured = TRUE;
[myAppDelegate loadEvents];
numberOfSections = 1;
_firstTab.selected = NO;
_secondTab.selected = YES;
} else if(_secondTab.selected && buttonTag != 2){
AppDelegate *myAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
myAppDelegate.isFeatured = FALSE;
[myAppDelegate loadEvents];
numberOfSections = 2;
_firstTab.selected = YES;
_secondTab.selected = NO;
}
[tableView reloadData];
}
Each time when I click on one of the buttons my xml its parsed and added into separate arrays; the arrays contains a list of events (eg. first section with now events and the 2nd one with the rest of them).
The problem which I have is when I have the 2nd button selected I have two section but sometimes my first section is empty so I don't want to display that section if its empty; please take a quick look to my code files...
Right now if my second tab (button) is selected I'm getting an empty table...
My code files are: myViewController and myAppDelegate
In your tableView datasource, implement this method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ( [self tableView:tableView numberOfRowsInSection:section] > 0 ) {
// INSERT YOUR HEADER STRING "times" array here.
return [NSString stringWithFormat:#"section %d",section];
} else {
return nil;
}
}
If it were me I would probably store my data in a 2d array then you will be able to have the following,
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [self.2darray count];
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.2darray objectAtIndex:section] count];
}
This will give you the correct number of sections and rows. Rather than trying to mess around with how many sections you have in these methods I would add,
(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if([[self.2darray objectAtIndex:section] count] <=0)
return 0;
return 44;
}
This is reasonably neat and tidy and will work irrespective of the number of rows and sections you create. Hope this helps.

UITableView issues

Iam adding objects to NSMutableArray and displaying the value in UITableView. Only the first object of the NSMutableArray is getting displayed.Where am i going wrong?
My Code snippet:
-(IBAction) segmentedControlIndexChanged:(id)sender {
int selectedSegment = ((UISegmentedControl*) sender).selectedSegmentIndex;
switch (selectedSegment) {
case 1: {
MatchSchedule *semiFinal1 = [[MatchSchedule alloc] initWithDeails:#"20 March"];
MatchSchedule *semiFinal2 = [[MatchSchedule alloc] initWithDeails:#"24 March"];
matchList = [[NSMutableArray alloc] initWithObjects:semiFinal1,semiFinal2,nil];
[semiFinal1 release];
[semiFinal2 release];
break;
}
default;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
....
MatchSchedule *matchSchedule = [knockoutStage objectAtIndex:indexPath.row];
cell.textLabel.text = matchSchedule.matchDate;
}
Hard to tell without seeing more of your code. Are you returning the correct value for
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [knockoutStage count];
}
?

iPhone - UITableView - lost data if i go back

I have a TabBar, NavBar, SearchBar with ScopeBar on my screen. I can search data via a remote server and list the content. So I have a NSMutableArray listContent and a filteredListContent like in the example of Apple (TableSearch - http://developer.apple.com/iphone/library/samplecode/TableSearch/index.html):
Now I added in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
these line:
testDetailViewController *testDetailViewController = [[TestDetailViewController alloc] initWithNibName:#"TestDetailView" bundle:[NSBundle mainBundle]];
testDetailViewController.title = testClass.name;
testDetailViewController.myKey = testClass.keyId;
[[self navigationController] pushViewController:testDetailViewController animated:YES];
[testDetailViewController release];
testDetailViewController = nil;
Because of the NavigationBar, there is a "back" button. If I click this button, the TableView is empty, no matches/hits.
What I have to do, so the content will still be there?
Does anyone know?
Thanks a lot in advance & Best Regards.
Source Code:
#implementation SearchViewController
#synthesize listContent, filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive;
- (void)viewDidLoad {
// restore search settings if they were saved in didReceiveMemoryWarning.
if (self.savedSearchTerm) {
[self.searchDisplayController setActive:self.searchWasActive];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
[self.searchDisplayController.searchBar setText:savedSearchTerm];
self.savedSearchTerm = nil;
}
}
- (void)viewDidUnload {
// Save the state of the search UI so that it can be restored if the view is re-created.
self.searchWasActive = [self.searchDisplayController isActive];
self.savedSearchTerm = [self.searchDisplayController.searchBar text];
self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
self.filteredListContent = nil;
}
- (void)dealloc {
[listContent release];
[filteredListContent release];
[super dealloc];
}
- (void)setData {
self.listContent = [NSMutableArray arrayWithCapacity:3];
[self.listContent addObject:[SearchObjects itemWithType:#"AAA" name:#"Test1"]];
[self.listContent addObject:[SearchObjects itemWithType:#"BBB" name:#"Test2"]];
[self.listContent addObject:[SearchObjects itemWithType:#"BBB" name:#"Test3"]];
// create a filtered list
self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];
[self.tableView reloadData];
self.tableView.scrollEnabled = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//If the requesting table view is the search display controller's table view, return the count of the filtered list, otherwise return the count of the main list.
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.filteredListContent count];
} else {
return [self.listContent count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
/* If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list. */
SearchObjects *searchObject = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
searchObject = [self.filteredListContent objectAtIndex:indexPath.row];
} else {
searchObject = [self.listContent objectAtIndex:indexPath.row];
}
cell.textLabel.text = searchObject.name;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// HERE IS THE SOURCE CODE FOR PUSHING TO THE NEXT VIEW
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// DO SOME CALCULATIONS… AND THE setData METHOD IS CALLED
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
/* Update the filtered array based on the search text and scope. */
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/* Search the main list for whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array. */
for (SearchObjects *searchObject in listContent) {
if ([scope isEqualToString:#"All"] || [searchObject.type isEqualToString:scope]) {
NSComparisonResult result = [searchObject.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame) {
[self.filteredListContent addObject:searchObject];
}
}
}
}
- (void)filterContentForScope:(NSString*)scope {
/* Update the filtered array based on the search text and scope. */
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/* Search the main list for whose type matches the scope (if selected); add items that match to the filtered array. */
for (SearchObjects *searchObject in listContent) {
if ([scope isEqualToString:#"All"] || [searchObject.type isEqualToString:scope]) {
[self.filteredListContent addObject:searchObject];
}
}
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForScope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForScope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
#end
You generally don't have to do anything in this case, the data should remain in place. Is there something which is unloading the data? Do you have a viewWillDisappear function which is unloading your array? Are you doing some of the array setup in viewWillAppear.
Put a log statement at the start of your methods to find out when they are being called, it will give you a clearer picture of what's happening.
It is solved. It was a problem which is not obvious with the given source code.
There was an error in my logic.