TableViewController , SearchBar and TableViewCell - objective-c

When I searching and after filtered select in displays row that opens only the first letter DetailView (for example A letter).Others letters don't open. NSLog and breakpoint not helping. I don't understand what is the problem.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *keyTitle = cell.textLabel.text;
NSDictionary *peopleUnderLetter = [self.propertyList objectForKey:self.letters[indexPath.section]];
__block NSDictionary *selectedPerson = nil;
[peopleUnderLetter enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([key isEqualToString:keyTitle]) {
selectedPerson = obj;
*stop = YES;
}
}];
if (selectedPerson) {
DetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"DetailViewController"];
// Push the view controller.
[self.navigationController pushViewController:vc animated:YES];
[vc setDictionaryGeter:selectedPerson];
}
}
#pragma mark Search Display Delegate Methods
-(void)searchDisplayController:(UISearchController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filteredNames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searchBar.text];
for (NSString *letter in letters) {
NSArray *matches = [[self.propertyList[letter] allKeys]filteredArrayUsingPredicate:predicate];
[filteredNames addObjectsFromArray:matches];
}
}
return YES;
}
after selecting every cell must open the detailviewcontroller with their data.Search bar shows every letter after filtered.But when I click cell doesn't open detail view (except first cell) .

Hard to tell without seeing the whole file but it looks like your problem may be this line. You are pulling the object out of self.propertyList using the section not the row. Which makes sense as to why it works only on the first row, which would have a row of 0 and an section of 0
`NSDictionary *peopleUnderLetter = [self.propertyList objectForKey:self.letters[indexPath.section]];`
Try changing it to :
`NSDictionary *peopleUnderLetter = [self.propertyList objectForKey:self.letters[indexPath.row]];`

Related

UISearch and TableViewCell

When I searching and then select row that opens only the first letter (for example A.Others letters don't open. NSLog and breakpoint not helping. I don't understand what is the problem.
#synthesize propertyList, letters, filteredNames, searchController , arrayPlace;
- (void)viewDidLoad {
[super viewDidLoad];
............
filteredNames = [[NSMutableArray alloc]init];
searchController = [[UISearchController alloc]init];
self.searchController.searchResultsUpdater = self;
NSString *path = [[NSBundle mainBundle] pathForResource:#"names" ofType:#"plist"];
self.propertyList = [NSDictionary dictionaryWithContentsOfFile:path];
self.letters = [[self.propertyList allKeys] sortedArrayUsingSelector:#selector(compare:)];
}
#pragma mark - Table view data source
.......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"cell bg1.png"]];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
if (tableView.tag == 1){
NSString *letter = self.letters[indexPath.section];;
NSArray *keyValues = [[self.propertyList[letter] allKeys] sortedArrayUsingSelector:#selector(compare:)];
cell.textLabel.text = keyValues[indexPath.row];
} else{
cell.textLabel.text = filteredNames[indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *keyTitle = cell.textLabel.text;
NSDictionary *peopleUnderLetter = [self.propertyList objectForKey:self.letters[indexPath.section]];
__block NSDictionary *selectedPerson = nil;
[peopleUnderLetter enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([key isEqualToString:keyTitle]) {
selectedPerson = obj;
*stop = YES;
}
}];
if (selectedPerson) {
DetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"DetailViewController"];
// Push the view controller.
[self.navigationController pushViewController:vc animated:YES];
[vc setDictionaryGeter:selectedPerson];
}
}
And :
#pragma mark Search Display Delegate Methods
-(void)searchDisplayController:(UISearchController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filteredNames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searchBar.text];
for (NSString *letter in letters) {
NSArray *matches = [[self.propertyList[letter] allKeys]filteredArrayUsingPredicate:predicate];
[filteredNames addObjectsFromArray:matches];
}
}
return YES;
}
Search bar fails and he does select row after searching
If you want more information just say it to me by answers and I will edit my question and then you will edit your answer
Please explain again clearly. You search using any alphabet, it shows the result which has only "A". Is this what you're trying to say ? If so, then remove the above code and try the below approach :-
Drag a search bar into the view controller and set its delegate to self (You'll find its property in the storyboard's delegate property
to the view controller).
Add UISearchBarDelegate in the .h file that will take care of automatically calling the appropriate methods of the search bar of
which the delegate is set to self.
Use the below method to detect the search. You can filter the NSArray here and reload the table.
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
}
I'd recommend you to go through some basic tutorials about iOS development before getting deeper. All the best and I hope it helps you...
Screenshot

Accessory checkmarks disappear when scrolling Objective-C

I have a tableview that I can add and remove multiple checkmarks. The only issue is if I put 3 checkmarks and scroll away, when I return the checkmarks are gone. I can't find anywhere on the internet a solution that works, and I've tried several variation and still nothing.
This is my code in cellForRowAtIndex that should be holding the checkmarks in place.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"contactCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
NSDictionary *contact = [self.tableData objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:1];
NSString *firstName = contact[#"firstName"];
nameLabel.text = [firstName stringByAppendingString:[NSString stringWithFormat:#" %#", contact[#"lastName"]]];
UILabel *phoneNumber = (UILabel *)[cell viewWithTag:2];
NSArray *phones = contact[#"phones"];
if ([phones count] > 0) {
NSDictionary *phoneItem = phones[0];
phoneNumber.text = phoneItem[#"value"];
}
UIImageView *cellIconView = (UIImageView *)[cell.contentView viewWithTag:888];
UIImage *image = contact[#"image"];
cellIconView.image = (image != nil) ? image : [UIImage imageNamed:#"smiley-face"];
cellIconView.contentScaleFactor = UIViewContentModeScaleAspectFill;
cellIconView.layer.cornerRadius = CGRectGetHeight(cellIconView.frame) / 2;
// Need to fix
if([checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
Here is the didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
{
UITableViewCell* checkCell = [tableView cellForRowAtIndexPath:indexPath];
if(checkCell.accessoryType == UITableViewCellAccessoryCheckmark)
{
checkCell.accessoryType = UITableViewCellAccessoryNone;
NSMutableArray *i = [[NSMutableArray alloc] init];
for (NSIndexPath *indexPath in [self.tableView indexPathsForSelectedRows]) {
[i addObject:self.tableData[indexPath.row]];
// Go inside pull the numbers from the users and save in an NSArray
// NSArray *contacts = i;
// self.recipients = [[NSMutableArray alloc] init];
for (NSDictionary* dict in i) {
// Grab phones
NSDictionary *contactNumber = [dict objectForKey:#"phones"];
for (NSDictionary* dict2 in contactNumber) {
// Grabs the phone numbers
NSString* value = [dict2 objectForKey:#"value"];
int index = [self.recipients indexOfObject:value];
[self.recipients removeObjectAtIndex:index];
[self.selectedUsers removeObjectAtIndex:index];
NSLog(#"The number that has a checkmark%#", value);
NSLog(#"the array of all%#", self.recipients);
NSLog(#"At index %lu", (unsigned long)[self.recipients indexOfObject:value]);
// [_recipients addObject:value];
}
}
// NSLog(#"Phone Numbers: %#",_recipients);
}
}
else
{
[self getNumber];
NSLog(#"clicking %#", self.recipients);
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
checkedIndexPath = indexPath;
}
}
I found The Solution:
You must save each indexPath into an array(put this code in didSelectRowAtIndexPath) and then in cellForRowAtIndexPath add the following code
if([self.checkedCells containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
Also in the didSelectRowAtIndexPath
Make sure to delete the indexPath when deselecting the row.
if(checkCell.accessoryType == UITableViewCellAccessoryCheckmark) {
checkCell.accessoryType = UITableViewCellAccessoryNone;
[self.checkedCells removeObject:indexPath];
I hope this helps someone. I been wrestling with this all day.
Make checkedIndexPath a #property (nonatomic, strong) and use self.checkedIndexPath whenever you refer to it. You're losing the reference after didSelectRowAtIndexPath exits. Set a breakpoint in cellForRowAtIndexPath and look at checkedIndexPath, I bet it's nil.
Maybe you should check if the isEqual functionality does what you expect. You could make sure by trying:
if (_checkedIndexPath.section == indexPath.section &&
_checkedIndexPath.row == indexPath.row)
If you still do not get the expected result, perhaps log the values of section and row to see where it goes wrong.
Please note that if for some reason _checkedIndexPath is a weak variable or gets deallocated, this check will fail.
You could also check that your cells are properly dequeued before being modified and that you are returning the correct cells.
If you want to store more than one checked row, of course, you will need more than one indexPath variable (just one _checkedIndexPath will not do it).

Objective-C didSelectRowAtIndexPath and serge to view controller

I am using a UITableViewController and didSelectRowAtIndexPath like so:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *type = [[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Type"];
if([type isEqualTOString: #"PDF"]){
//GOTO View Controller
}else{
NSArray *elements = [[[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Name"] componentsSeparatedByString:#"FTP\\"];
currentPath = [[[[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Name"] componentsSeparatedByString:#"FTP\\"] lastObject];
NSString *escapedString = [elements[1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
self.tableData = [dataSource.areaData GetFilesAndDirectories:[NSString stringWithFormat:#"%#",escapedString]];
[self.tableView reloadData];
}
}
is what I am trying to do possible? If the type is PDF goto the view Controller, else just update the table view.
Currently, When I select a row, it goes to View Controller, everytime.
This is what I got:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *type = [[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Type"];
if([type isEqualToString: #"Directory"]){
NSArray *elements = [[[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Name"] componentsSeparatedByString:#"FTP\\"];
currentPath = [[[[self.tableData objectAtIndex:indexPath.row] objectForKey:#"Name"] componentsSeparatedByString:#"FTP\\"] lastObject];
NSString *escapedString = [elements[1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
self.tableData = [dataSource.areaData GetFilesAndDirectories:[NSString stringWithFormat:#"%#",escapedString]];
[self.tableView reloadData];
}else{
[self performSegueWithIdentifier:#"showDetail" sender:self.view];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showDetail"])
{
NSLog(#"Here");
}
}
But it still goes to the View Controller everytime.
Yes it is possible.
In the PDF if you should Create the view controller you want to present and then call the presentViewController:animated:completion: method of the current view controller, passing in the PDF view controller you want.
EDIT: I didn't see the edited last sentence.
The only issue i found is a misstype in isEqualToString function and the chance that your type string could be nil.
EDIT 2:
I add an example of my own code. In this case the view allways open, but its different depending of the content if.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger row = [indexPath row];
locationData *locData;
if (indexPath.section == 0) {
locData= [self.sortEDlocations objectAtIndex:row];
}
else {
if(_btnUrgentCareFilter.isSelected){
locData = [self.filterSortOtherLocations objectAtIndex:row];
}else{
locData = [self.sortOtherLocations objectAtIndex:row];
}
}
[self showDetailView:locData];
}

How to add Pagination to Tableview on Search results?

The following lines of code shown below are my current tableview settings. What i would like to achieve is what's seen on the image below.
1) if count is 4 when user scrolls Down show a Activity Indicator and Make a request using the next value shown on the JSON Below.
2) Reload the Table
3) Show No more results if count is empty.
Note: I am new on Objective-C so I will appreciate your guidance on this subject since all searches I have done were not successful on what I am looking to achieve since all of them are based on a table already loaded and not based on a Search Result.
As shown on the Image Below is a reference what i want to achieve.
JSON RESPONSE FROM SEARCH
{
"count": 4,
"next": "http://api.domain.com/user-search/?page=2&subject=culture",
"previous": null,
"results": [
{
"name": "Guillermo Davila",
"nick": "guillermo",
"avatar_s": "https://pbs.twimg.com/profile_images/2213685686/image.jpg",
"user_rate": "$10/h",
"id": 3,
"subjects": "Culture and 1 other subject",
"bio": "I'm a nice person"
},
{
"name": "Frank Smith",
"nick": "fsmith",
"avatar_s": "https://pbs.twimg.com/profile_images/2444486/image.jpg",
"user_rate": "$14/h",
"id": 3,
"subjects": "Culture and 1 other subject",
"bio": "I'm a nice person 2"
}
]
}
And here is my UserTableviewController.h
//
// UserTableViewController.m
// mobile-app
//
// Created by eddwinpaz on 5/18/14.
// Copyright (c) 2014 eddwinpaz. All rights reserved.
//
#import "UserTableViewController.h"
#import "CustomTableCell.h"
#import "UserDetailViewController.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "SimpleAudioPlayer.h"
#interface UserTableViewController ()
#end
#implementation UserTableViewController
{
// JSON Request
NSMutableArray *myObject;
// A Dictionary Object
NSDictionary *dictionary;
NSString *name;
NSString *subject;
NSString *avatar;
NSString *rate;
NSString *bio;
NSString *nick;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//[self fetch_tutors]; // Get tutors Ordered By Karma DESC
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (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 0;
} */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return myObject.count; // This is old 100% working code
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
dictionary = [myObject objectAtIndex:indexPath.row];
cell.labelName.text = [dictionary objectForKey:#"name"];
cell.labelBio.text = [dictionary objectForKey:#"bio"];
cell.labelSubjects.text = [dictionary objectForKey:#"subject"];
cell.imageAvatar.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dictionary objectForKey:#"avatar"]]]];
cell.imageAvatar.clipsToBounds = YES;
cell.imageAvatar.layer.cornerRadius = cell.imageAvatar.frame.size.width / 2;
cell.labelRate.text = [dictionary objectForKey:#"rate"];
cell.labelRate.layer.cornerRadius = 5;
[SimpleAudioPlayer playFile:#"upvote.wav"];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showUserDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UserDetailViewController *destViewController = segue.destinationViewController;
NSDictionary *dict = [myObject objectAtIndex:indexPath.row];
destViewController.http_nick = [dict valueForKey:#"nick"];
destViewController.labelName = [dict valueForKey:#"name"];
NSLog(#" Username Sent--->%#", [dict valueForKey:#"nick"]);
NSLog(#" name Sent--->%#", [dict valueForKey:#"name"]);
}
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
NSString *searchTerm = searchBar.text;
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Searching Tutors";
[hud show:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *url = [NSString stringWithFormat:#"http://api.domain.com/user-search/?subject=%#",searchTerm];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
[hud hide:YES];
int count_total = [[responseObject objectForKey:#"count"] intValue];
if (count_total == 0) {
[myObject removeAllObjects];
NSLog(#"Count is --->0");
}
else {
myObject = [[NSMutableArray alloc] init];
name = #"name";
subject = #"subject";
avatar = #"avatar";
rate = #"rate";
bio = #"bio";
nick = #"nick";
for (NSDictionary *dataDict in [responseObject objectForKey:#"results"])
{
NSString *name_data = [dataDict objectForKey:#"name"];
NSString *subject_data = [dataDict objectForKey:#"subjects"];
NSString *avatar_data = [dataDict objectForKey:#"avatar_s"];
NSString *rate_data = [dataDict objectForKey:#"user_rate"];
NSString *bio_data = [dataDict objectForKey:#"bio"];
NSString *nick_data = [dataDict objectForKey:#"nick"];
NSLog(#"name: %#", name_data);
NSLog(#"subjects: %#",subject_data);
NSLog(#"avatar_s: %#", avatar_data);
NSLog(#"user_rate: %#",rate_data);
NSLog(#"bio: %#",bio_data);
NSLog(#"nick: %#",nick_data);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
name_data,name,
subject_data,subject,
avatar_data,avatar,
rate_data,rate,
bio_data, bio,
nick_data, nick, nil];
[myObject addObject:dictionary];
}
}
[self.searchBar endEditing:YES];
[self.searchBar setShowsCancelButton:NO animated:YES];
[self.searchBar sizeToFit];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
[hud hide:YES];
}];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[self.searchBar endEditing:YES];
[searchBar setShowsCancelButton:NO animated:YES];
self.searchBar.text = nil;
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"userDetailView"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UserDetailViewController *destViewController = segue.destinationViewController;
destViewController.labelName = [myObject objectAtIndex:indexPath.row];
}
} */
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
One way to achieve it is,
Return the numberOfCells as one more than the data array
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return myDataArray +1 ; //myDataArray is the data and One more cell for the last cell (10 out of 46 results cell)
}
In cellForRowAtIndexPath, if your IndexPath.row == myDataArray.count (ie., Last Row) Create a custom cell which looks as in the picture and return the custom cell.
In - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath, If the indexPath corresponds to last cell, then Start Request for page 2, once the results are fetched, update the myDataArray and reload the table.

Segue doesn't work because of searchbar

I have made a table where depending on which cell you click on you will be sent into a new scene (detailviewcontroller). For example if you click on the cell with the text Thailand you will be sent to ThailandDetailViewController (scene). Everything works until you use the searchbar (look under - (void)tableView).
-When some countries get outfiltered (because of the searchfunction) the reaming countries will go higher in the table and acquire a lower count. Which leads to that they will lead to the wrong detailviewcontroller (scene).
A friend of mine said to me that I should use objectAtIndex within my array, didnt really catch what he meant with that.. And make a switch on the cell.textLabel.text (didnt really follow him)
Here is my .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
self.mySearchBar.delegate = self;
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
totalStrings = [[NSMutableArray alloc] initWithObjects:#"America",#"Austria",#"Canada",#"France",#"Germany",#"Greece",#"Malaysia",#"Mexico",#"Netherlands",#"Poland",#"Russia",#"Singapore",#"Thailand",#"Ukraine", nil];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case 0: [self performSegueWithIdentifier:#"Segue0" sender:self];
break;
case 1: [self performSegueWithIdentifier:#"Segue1" sender:self];
break;
//and so on
default: break;
}
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0){
isFiltered = NO;
}
else
{
isFiltered = YES;
filteredStrings = [[NSMutableArray alloc]init];
for (NSString *str in totalStrings){
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound) {
[filteredStrings addObject:str];
}
}
}
[self.myTableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cellidentifier];
}
if (!isFiltered) {
cell.textLabel.text = [totalStrings objectAtIndex:indexPath.row];
}
else //if it's filtered
{
cell.textLabel.text = [filteredStrings objectAtIndex:indexPath.row];
}
return cell;
}
Big thank you in beforehand!!
Well, you can have a custom class to store the area and the segue index like this:
#interface SegueVO : NSObject
#property (nonatomic, strong) NSString *area;
#property int segueIndex;
-(id)initWithArea:(NSString *)area andSegueIndex:(int)index;
#end
#implementation SegueVO
-(id)initWithArea:(NSString *)area andSegueIndex:(int)index
{
self = [super init];
if (self)
{
self.area = area;
self.segueIndex = index;
}
return self;
}
#end
You will then store your ares in the totalStrings array like this:
[[NSMutableArray alloc] initWithObjects:[[SegueVO alloc] initWithArea:#"America" andIndex:0],....
Of course you can create a factory method to cut down on initialisation code.
Now you can work out what segue to activate like this:
NSArray *arrayToUse = totalStrings;
if (isFiltered)
arrayToUse = filteredStrings;
[self performSegueWithIdentifier:[#"Segue"
stringByAppendingString:[NSString stringWithFormat:#"%i",
[arrayToUse[indexPath.row].segueIndex]] sender:self];
Hope this helps.
You could easily solve this problem by storing a custom object in your table's data model instead of an NSString. That object would contain the label to display plus the name of the segue to activate once selected.
It's another question why you'd want a totally different view controller for different data. I suppose these are different kinds of data that need different ways to deal with them.