grouping rows into sections or groups IOS - ios

i am working on a Xcode 5.0.2 . i am following these lynda tutorials. the problem is i am not able to create section or groups of tableView as in one of the video.. i have changed table view to grouped too,but it is displaying only one section.
here is my code
#implementation ViewController {
NSDictionary *courseDetails;
NSArray *justCourseNames;
NSDictionary *webCourseDetails;
NSArray *webCourseNames;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section==0) {
return #"iOS Courses";
} else {
return #"Web Courses";
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section==0) {
return courseDetails.count;
} else {
return webCourseDetails.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"]; /
if(indexPath.section==0) {
cell.textLabel.text = justCourseNames[indexPath.row];
} else {
cell.textLabel.text = webCourseNames[indexPath.row];
}
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"courses" withExtension:#"plist"];
courseDetails = [NSDictionary dictionaryWithContentsOfURL:url];
justCourseNames = courseDetails.allKeys;
NSURL *urlWeb = [[NSBundle mainBundle] URLForResource:#"courses_web" withExtension:#"plist"];
webCourseDetails = [NSDictionary dictionaryWithContentsOfURL:urlWeb];
webCourseNames = webCourseDetails.allKeys;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

I don't see anything wrong in the code provided. Just make sure you set the dataSource to your tableView. In storyboard the easiest way is to control-drag from the tableView to the ViewController in the object outline and select dataSource from the menu on release.

The issue was the simulator which wasn't populating all rows.
I have restarted the simulator and now it works fine.

Related

UIButton doesn't appear on iOS Today Widget

I am creating a today extension for my app, but there are some errors that I can't quite understand:
First:
Everything is Ok on the storyboard, but the button doesn't appear on the widget.
Second: When the tableview has more than one cell, the last cell gets cut.
Third: CellForRow is called, but don't change anything on the cell (Label is still "Label").
http://i.stack.imgur.com/Jp31V.png
Here's my Widget code:
#implementation TodayViewController{
NSMutableArray *listaFavoritos;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.widgetTableView.delegate = self;
self.widgetTableView.dataSource = self;
[self updateTableView];
self.preferredContentSize = self.widgetTableView.frame.size;
}
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResultFailed
// If there's no update required, use NCUpdateResultNoData
// If there's an update, use NCUpdateResultNewData
completionHandler(NCUpdateResultNewData);
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
}
return self;
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
[self updateTableView];
}
- (void)updateTableView {
listaFavoritos = [[NSMutableArray alloc] init];
//listaFavoritos = [[self readArrayWithCustomObjFromUserDefaults:#"listaFavs"] mutableCopy];
[listaFavoritos addObject:#"test1"];
[listaFavoritos addObject:#"test2"];
NSLog(#"%#", listaFavoritos);
}
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName
{
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:#"group.com.kazoowa.timers"];
NSData *data = [sharedDefaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[sharedDefaults synchronize];
return myArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listaFavoritos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"WidgetCell" forIndexPath:indexPath];
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
NSLog(#"CellForRow");
return cell;
}
1)For your second problem, your cellIdentifier in tableView:cellForRowAtIndexPath will be "static" like this :
static NSString *cellName = #"WidgetCell";
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName forIndexPath:indexPath];
2)this condition will be never execute because it's never nil :
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
replace it by this :
if (cell != nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
3)Please use Pragma Mark for separate properly your code like below:
#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listaFavoritos count];
}
#pragma mark-UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"WidgetCell" forIndexPath:indexPath];
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
NSLog(#"CellForRow");
return cell;
}
Hope it helps :)
Try it :
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellName = #"WidgetCell";
WidgetTableViewCell *cell = (WidgetTableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellName];
if (cell == nil) {
cell = [[WidgetTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
}
cell.textLabel.text = [listaFavoritos objectAtIndex:indexPath.row];;
return cell;
}

sectioned table view returning blank table

I found code examples online for creating a tableview with alphabetical sections and i have tried to adapt for my tableview.
However, now the simulator is returning a blank table.
I've obviously gone wrong, anyone mind pointing out the mistakes?
Every change I make doesn't help.
Thank you
#import "RCViewController.h"
#interface RCViewController ()
#end
#implementation RCViewController
#synthesize content = _content;
#synthesize sectionData;
#synthesize sectionNames;
-(NSArray *)content {
NSArray *words = [NSArray arrayWithObjects:#"Tee", #"Club", #"Green", #"Putt", nil];
NSArray *sortedWords = [words sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSString *currentLetter = #"";
for (NSString *string in sortedWords) {
if (string.length>0) {
NSString *letter = [string substringToIndex:1];
if (![letter isEqualToString:currentLetter]) {
[sectionNames addObject:letter];
currentLetter = letter;
NSMutableArray *oneSection = [NSMutableArray array];
[sectionData addObject:oneSection];
[[sectionData lastObject]addObject:string];
}
}
}
return _content;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionNames.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[sectionData objectAtIndex:section]count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionNames objectAtIndex:section];
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return sectionNames;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"simpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
cell.textLabel.text =[[self.sectionData objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
}
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
There are a bunch of things that are not optimal with your code but what is causing the table to be blank is most likely that you are never populating sectionData and sectionName and so it returns a table with no section names or section data. Try this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *words = [NSArray arrayWithObjects:#"Tee", #"Club", #"Green", #"Putt", nil];
NSArray *sortedWords = [words sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSString *currentLetter = #"";
for (NSString *string in sortedWords) {
if (string.length>0) {
NSString *letter = [string substringToIndex:1];
if (![letter isEqualToString:currentLetter]) {
[sectionNames addObject:letter];
currentLetter = letter;
NSMutableArray *oneSection = [NSMutableArray array];
[sectionData addObject:oneSection];
[[sectionData lastObject]addObject:string];
}
}
}
}

Changed my code from previous. How to link tableview cells to specfic blog posts?

I've hardcoded all of the titles of my cells, and am looking to link each individual cell to a different blog post. The section titles are my keys, and the values are an array of the information pertaining to the title. How would I go about this? I'm a bit confused because due to the fact I have sections, the row selected number restarts as I begin the next section. There's some code involving a search bar so disregard that. An example would be so helpful!
#interface InfoTableViewController () {
NSDictionary *names;
NSArray *sectionTitles;
}
#end
#implementation InfoTableViewController {
NSArray *items;
NSArray *searchResults;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
names = #{#"Green Manual" : #[#"Basic Rules", #"Pledge Mom Interview", #"Pledge Class Song", #"Code of Conduct", #"History of XXX", #"Founding Sisters of XX", #"Inter-Chapter Council", #"General Facts", #"Crest of XXX", #"Sister of Mine", #"Greek Alphabet", #"Delta Chapter History",#"Actives", #"Associates, Recessives, Retired Actives, Inactives", #"Alumnae", #"Family Tree"],
#"Interviews" : #[#"Alyson Au", #"Jazzmin Boo", #"Shuki Chan", #"Ivy Cheng", #"Julie Ha", #"Jenny Hong", #"Linde Huang", #"Erica Jon", #"Jenny Lau", #"Jean Lin", #"Vivian Lo", #"Jackie Nguyen", #"Nhi Nguyen", #"Sarah Pham", #"Jasmine Ta", #"Diane Tran", #"Joyce Wong", #"Kathie Wong", #"Jennifer Xu"]};
sectionTitles = [[names allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [sectionTitles count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *sectionTitle = [sectionTitles objectAtIndex:section];
NSArray *sectionNames = [names objectForKey:sectionTitle];
return [sectionNames count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionTitles objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath
{
//static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *sectionTitle = [sectionTitles objectAtIndex:indexPath.section];
NSArray *sectionNames = [names objectForKey:sectionTitle];
NSString *name = [sectionNames objectAtIndex:indexPath.row];
cell.textLabel.text = name;
NSLog(#"Row selected: %d", indexPath.row);
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"name BEGINSWITH[cd] %#", searchText];
searchResults = [items filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
I assume you are trying to select a cell and detect that in order to move to a different controller, which then would display some of your content.
Even though you have
NSLog(#"Row selected: %d", indexPath.row);
in your method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath
That's not the method that actually detects a cell selection. You should use:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
which is a method from TableViewDelegate, and not TableViewDataSource. Your controller needs to implement both. You also need to connect your tableView to your delegate, in this case, your own controller.
Try NSLogging inside didSelectRowAtIndexPath method to track your selection and further push a new controller, or perform a Storyboard Segue.

loading list of nearby places iOS 7 using simulator

I am using MapKit and I'm trying to retrieve a list of nearby places based on the users current location and after that, I am trying to display them in a TableView. However, when using the iOS simulator, no places show up. I went to simulator->debug->location->Apple so shouldn't results pertaining to THAT location show up? I'm confused. Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
//[self CurrentLocationIdentifier];
[self performSearch];
_m= [MKMapItem mapItemForCurrentLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _places.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"placeCell";
PlaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
long row = [indexPath row];
cell.placeLabel.text = _places[row];
return cell;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[super tableView:tableView didDeselectRowAtIndexPath:indexPath];
int rowNo = indexPath.row;
_place = [_places objectAtIndex:rowNo];
}
- (void) performSearch {
MKLocalSearchRequest *request =
[[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = _m.name;
_places = [[NSMutableArray alloc] init];
MKLocalSearch *search =
[[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
NSString *n = item.name;
[_places addObject:n];
}
}];
}
#end
You need to add a bunch of log statements and look at what is displayed in the console (or add breakpoints and use the debugger, but I'm guessing you don't know how to do that.
Add a log statement at the beginning of your performSearch that displays the _m.name that you are using as your search string. Add a log to the top of your completion handler so you know that it's called.
Okay so for some reason the results started appearing after I changed the type of "row" in cellForRowAtIndexPath from long to int and instead of [indexPath row], I changed it to indexPath.row

UITableView cells not being populated [duplicate]

This question already has an answer here:
ios - why does my UITableView not get populated with comments
(1 answer)
Closed 9 years ago.
I am getting a list of some ShoppingLists through a WCF call.
My code:
#import "ListTableViewController.h"
#import "ListServiceSvc.h"
#interface ListTableViewController (){
// NSMutableArray *shoppingLists;
}
#property (nonatomic, retain) NSMutableArray *shoppingList;
#end
#implementation ListTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
_shoppingList = [NSMutableArray array];
[self loadListsFromRemoteServer];
[super viewDidLoad];
}
-(void) loadListsFromRemoteServer
{
NSString *uname = #"Test4";
NemListBinding *binding = [[ListServiceSvc NemListBinding]initWithAddress:#"http://balder.ucn.dk/dm76_gr5/WCF.ListService.svc/custom?singleWsdl"];
binding.logXMLInOut=YES;
ListServiceSvc_GetShoppingListsWithUname *parms = [[ListServiceSvc_GetShoppingListsWithUname alloc]init];
parms.uname = uname;
[binding GetShoppingListsWithUnameAsyncUsingParameters:parms delegate:self];
}
- (void) operation:(NemListBindingOperation *)operation completedWithResponse:(NemListBindingResponse *)response
{
NSArray *responseHeaders = response.headers;
NSArray *responseBodyParts = response.bodyParts;
//[NSThread sleepForTimeInterval:5.0];
NSMutableArray *shoppingListFromWebserver = [[NSMutableArray alloc] init];
// step 1 fill in the blanks.
for(id header in responseHeaders) {
// here do what you want with the headers, if there's anything of value in them
}
for (id mine in responseBodyParts)
{
if ([mine isKindOfClass:[ListServiceSvc_GetShoppingListsWithUnameResponse class]])
{
for (id slist in [[mine GetShoppingListsWithUnameResult] ShoppingList])
{
[shoppingListFromWebserver addObject:slist];
NSLog(#"new list :: RESPONSE FROM SERVER :: nList %#", [slist ShoppingListName]);
//self.result.text = [self.result.text stringByAppendingString:[slist shoppingListName]];
}
}
}
[self performSelectorOnMainThread:#selector(updateNewView:) withObject:shoppingListFromWebserver waitUntilDone:NO];
}
-(void) updateNewView:(NSMutableArray*) result
{
_shoppingList = result;
NSLog( #"new list - number of news :: %u", [_shoppingList count]);
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
// return _shoppingList.count;
//}
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
// // Return the number of rows in the section.
// return 10;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cellforrow");
static NSString *CellIdentifier = #"ListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
id shopList = [_shoppingList objectAtIndex:indexPath.row];
cell.textLabel.text = [shopList ShoppingListName];
return cell;
}
Nothing happens when i run the app in Xcode. I can see in the log window that the log
NSLog( #"new list - number of news :: %u", [_shoppingList count]);
does return a value (4), but the NSLog i have made in the CellForRowAtIndexPath method does not get printed. I also have a breakpoint in there, that isn't reached. Why is it not getting to the method?
These methods, numberOfSectionsInTableView and numberOfRowsInSection are important to determine what number of data the TableView should show.. it should look something like this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1; // the number of different sections in your table view
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_shoppingList count]; // the number of data in your shopping list
}
You should not comment out these methods: numberOfSectionsInTableView and numberOfRowsInSection.
At least numberOfRowsInSection is required and must return the number of rows you want/need.
As far as I got it, this should be _shoppingList.count in your case.
because you commented out these methods: numberOfSectionsInTableView and numberOfRowsInSection, your tableView would be 0 section and 0 row,so the method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
did not be accessed.

Resources