UISearchbarController is returning a wrong indexpath? - ios

Im working on a tableview with a searchBardisplayController but when I type a search this shows the correct results but when I select the cell shows me a different selection (such as if I select a cell when the tableview is normal, the normal indexpath)
So heres my code:
number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// NSLog(#"%i", [[InfoWebDoctores sharedInstance]numberOfInfo]);
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [displayObject count];
} else {
return [allObject count];
}
}
Configure the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"docCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"docCell"];
}
return cell;
}
Make the search:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
if([searchString length] == 0)
{
[displayObject removeAllObjects];
[displayObject addObjectsFromArray:allObject];
}
else
{
[displayObject removeAllObjects];
for(NSDictionary *tmpDict in allObject)
{
NSString *val = [tmpDict objectForKey:doctorname];
NSRange r = [val rangeOfString:searchString options:NSCaseInsensitiveSearch];
NSString *val2 = [tmpDict objectForKey:doctoresp];
NSRange r2 = [val2 rangeOfString:searchString options:NSCaseInsensitiveSearch];
if(r2.location != NSNotFound || r.location != NSNotFound)
{
[displayObject addObject:tmpDict];
}
}
}
return YES;
}
And finally sending the data to the detailViewcontroller (Ive tryied with push connection but when I select a searchresult Cell not even get the push view...)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
DetailTableViewController *detail = [self.storyboard instantiateViewControllerWithIdentifier:#"detailController"];
NSIndexPath *index = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
//NSIndexPath *index = [self.tableView indexPathForSelectedRow];
int row = [index row];
EntryJsonDoctores *entry = [[InfoWebDoctores sharedInstance]entryAtIndex:row];
detail.modal = #[entry.nombre,entry.especialidad, entry.especialidad2, entry.especialidad3, entry.cel, entry.mail, entry.tel1, entry.tel2, entry.ext,entry.hospital,entry.direccion];
[self presentViewController:detail animated:YES completion:^{
}];
}
So Ive tryied with the indexpathforselectedrow from the tableview and the indexpath from searchresultscontroller, whats wrong? I need someones help please

If you set the search display controller's resultsTableView's delegate to this View Controller, then the results TableView will be looking for the didSelectRowAtIndexPath.
You can do this in the viewDidLoad and put self.searchDisplayController.searchResultsTableView.delegate = self
Replace NSIndexPath *index = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow]; with NSIndexPath *index = indexPath;

Related

Objective-c PushView for a cell of TableView in an other TableView

I have a problem by showing detail for a selected cell. But this cell is in a TableView horizontal, and this TableView is in a cell of an other TableViewController. I hope you can understand me.
Here the code of the TableViewController (named HostingTableViewController) :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellWithTableInside";
CellWithTableInside *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CellWithTableInside alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor blackColor];
NSArray *tabSection = [dictionarySection keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare:obj2];
}];
NSArray* sortedNumbers = [tabSection sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
id key,value;
key = [sortedNumbers objectAtIndex: [indexPath section]];
value = [dictionarySection objectForKey: key];
[cell setCellData:[dictionaryClip objectForKey:key]];
return cell;
}
Here the code for the Cell for show the detail controller :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailClip *secondVC = [[DetailClip alloc]initWithClip:[array objectAtIndex:[indexPath row]]];
[pushVC.navigationController pushViewController:secondVC animated:YES];
}
pushVC is init here :
pushVC = [[HostingTableViewController alloc]init];
Let me know if you need more informations, or code.
Thanks in advance :)
If you confused in adding code on cell tap you can compare the tables & add the action by comparing its type (name of table)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView==NameOfYourFirstTable)//first table view cell tap
{
//write the code for your action
DetailClip *secondVC = [[DetailClip alloc]initWithClip:[array objectAtIndex:[indexPath row]]];
[pushVC.navigationController pushViewController:secondVC animated:YES];
}
else
{
//actions on click of other table view cell
}
}

How to move cell without NSIndexPath in UITableView?

I am going to move a cell from a section to another in UITableView. The problem is that I don't know the index path of this cell. (Or in other words, I have an index path for this cell but the index path is likely out of date now). Instead, I have a reference point to this cell. How can I move this cell?
thanks in advance.
Here is an example of how to move a row based on finding a certain string in the cell to the top of section 1.
#implementation TableController {
NSInteger selectedRow;
NSMutableArray *theData;
}
-(void)viewDidLoad {
[super viewDidLoad];
self.tableView.contentInset = UIEdgeInsetsMake(70, 0, 0, 0);
NSMutableArray *colors = [#[#"Black", #"Brown", #"Red", #"Orange", #"Yellow",#"Green", #"Blue"] mutableCopy];
NSMutableArray *nums = [#[#"One", #"Two", #"Three", #"Four", #"Five", #"Six", #"Seven", #"Eight"] mutableCopy];
theData = [#[colors, nums] mutableCopy];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return theData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [theData[section] count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return (section == 0)? #"Colors" : #"Numbers";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = theData[indexPath.section][indexPath.row];
return cell;
}
-(IBAction)moveRow:(id)sender {
NSString *objToMove = #"Red";
// Find the section that contains "Red"
NSInteger sectionNum = [theData indexOfObjectPassingTest:^BOOL(NSArray *obj, NSUInteger idx, BOOL *stop) {
return [obj containsObject:objToMove];
}];
// Find the row that contains "Red"
NSInteger rowNum = [theData[sectionNum] indexOfObjectIdenticalTo:objToMove];
if (sectionNum != NSNotFound && rowNum != NSNotFound) {
[theData[sectionNum] removeObjectIdenticalTo:objToMove];
[theData[1] insertObject:objToMove atIndex:0];
[self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:rowNum inSection:sectionNum] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
}
}
If you have a reference to the cell's object then you can simply get its indexpath.
UITableViewCell *cellObject; //provided that you have a reference to it.
NSIndexPath *indexPath = [tableView indexPathForCell:cellObject];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

How to add a search bar and search display to an rss feed in UItableview

I created an RSS reader that parses from a .xml file. I am trying to create a search bar and search display controller, but am not sure how to search the objectForKey "title" or objectForKey "summary" within the UITableView.
Any help would be greatly appreciated.
The numberOfRowsInSection and cellForRowAtIndexPath looked like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
I recently tried to follow this sample project - https://github.com/deepthit/TableViewSearch.git - based on a suggestion.
My code then looked like this:
#interface QldRecentJudgmentsViewController () {
__strong NSArray *mFilteredArray_;
__strong UISearchBar *mSearchBar_;
__strong UISearchDisplayController *mSearchDisplayController_;
}
#end
#implementation ViewController
#synthesize parseResults = _parseResults, HUD;
- (void)viewDidLoad {
[super viewDidLoad];
mSearchBar_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0,
0,
self.view.bounds.size.width,
44)];
mSearchBar_.delegate = self;
mSearchBar_.placeholder = #"search";
self.tableView.tableHeaderView = mSearchBar_;
mSearchDisplayController_ = [[UISearchDisplayController alloc] initWithSearchBar:mSearchBar_
contentsController:self];
mSearchDisplayController_.searchResultsDelegate = self;
mSearchDisplayController_.searchResultsDataSource = self;
mSearchDisplayController_.delegate = self;
}
#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 self.parseResults.count;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
return [mFilteredArray_ count];
}
return parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id result;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
result = [mFilteredArray_ objectAtIndex:indexPath.row];
}
else
{
result = [parseResults objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *url = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"link"];
NSString *title = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
WebViewController *viewController = [[WebViewController alloc] initWithURL:url title:title];
[self.navigationController pushViewController:viewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
if ([searchText length] == 0)
{
[self.tableView reloadData];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.title contains[cd] %# OR SELF.summary contains[cd] %#", searchText, searchText];
mFilteredArray_ = [self.parseResults filteredArrayUsingPredicate:predicate];
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
mFilteredArray_ = nil;
[self.tableView reloadData];
}
However, when I follow this the RSS feed does not load anymore in the tableview, so there are no results. Nevertheless when I try to search it does not correctly search the "title" or "summary" and the search results do not appear correctly -the cells are not neatly aligned after searching for something and getting results. Also, the only way to see RSS in the tableview is to search for any generic string, but once you press cancel in the search bar the RSS feed disappears and shows an empty tableview.
Thanks for any help in advance.

iOS Search Address book contacts by UISearchBar using NSDictionary with multiple arrays

I am trying to implement search bar in my custom Contacts Book. I created NSDictionary for search data and added to my dictionary 4 mutable arrays, include
names, last name, phone types, phone numbers.
When I am trying to search in NSDictionary, my app is crashing on cell create. And When I am searching by one array only (from dictionary valueforkey or directly from array) it's working partially, but taking another strings (for example last name) always from the first contact in the list. Bacause not all parameters in a loop, So I have to search by every parameter to get right first name and last name in my contacts.
here is my code:
#pragma mark SEARCH_BAR
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.tableSearchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)serachBar textDidChange:(NSString *)searchText {
[filteredStrings removeAllObjects];
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
//here aim creating NSDictionary with 4 Mutable Arrays
NSDictionary *filteredContacts = [NSDictionary dictionaryWithObjectsAndKeys:
contacts.firstNames, #"First Name",
contacts.lastNames, #"Last Name",
contacts.phoneTypes, #"Phone Type",
contacts.phoneNumbers, #"Phone Numbers",
nil];
//[filteredStrings addObject:filteredContacts];
for (NSString *str in filteredContacts) { // in this case for (NSString *str in [filteredContacts valueForKey:#"First Name"]) all working partially
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
filteredStrings = [[NSMutableArray alloc]init];
[filteredStrings addObject:str];
}
}
}
[self.contactsTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [filteredStrings count];
}
return [contacts.firstNames count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
abCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
}
if (!isFiltered) {
cell.firstNameLabel.text = [contacts.firstNames objectAtIndex:indexPath.row];
cell.lastNameLabel.text = [contacts.lastNames objectAtIndex:indexPath.row];
cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
} else {
cell.firstNameLabel.text = [filteredStrings objectAtIndex:indexPath.row]; // Here my app is crashing when trying to search by all nsdictionary.
cell.lastNameLabel.text = [filteredStrings objectAtIndex:indexPath.row];
//cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.contactsTableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"NextView"]) {
//if (!isFiltered) {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
//}
/*else {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
}*/
}
}

UITableView cell not display correct detail

I created tableview and searchbar.
Name for cell 1 is iPhone.
When I click on the cell iPhone, on detail view it writes iPhone. When I search iPod it became the first cell in the search list but when I click this ,it writes iPhone instead of iPod. I try insert all code to here.
- (BOOL)shouldAutootateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table View Methods
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [displayItems count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
return cell;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if ([searchText length] == 0) {
[displayItems removeAllObjects];
[displayItems addObjectsFromArray:allItems];
} else {
[displayItems removeAllObjects];
for (NSString * string in allItems ){
NSRange r =[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
[displayItems addObject:string];
}
}
[tableView reloadData];
}
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar {
[searchBar resignFirstResponder];
}
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryDisclosureIndicator;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *DVC = [[DetailViewController alloc] init];
//Pass the row to the DVC
DVC.characterNumber = [indexPath row];
//Push the DetailViewController object onto the stack
[self.navigationController pushViewController:DVC animated:YES];
}
#end
You are passing to detail controller row number for allItems array, but it is not same that in displayItems
DVC.characterNumber = [indexPath row];
There is you should assing correct row from allItems array, not displayItems array
Update:
NSString *item = [displayItems objectAtIndex:indexPath.row;
DVC.characterNumber = [allItems indexOfObject:item];

Resources