uisearchdisaplycontroller inside uiviewcontrolelr - programmatically - uitableview

I create a UIViewController with a UITableView and UISearchDisplayController, the problem is that shouldReloadTableForSearchString not run...this is my code, where is the mistake for you?
- (void)viewDidLoad {
[super viewDidLoad];
array = [[NSMutableArray alloc] initWithObjects:#"ciao",#"mandi",#"viva",#"blabla", nil];
arrayFiltrato = [[NSMutableArray alloc] initWithObjects:#"ciao",#"mandi",#"viva",#"blabla", nil];
//[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
[self.tableView reloadData];
[self setSearchBar];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self.navigationController setNavigationBarHidden: NO];
}
- (void) setSearchBar {
self.searchBar = [[UISearchBar alloc] init];
[self.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[self.searchBar setPlaceholder:#"Type a search term" ];
[self.searchBar setTintColor:[UIColor blackColor]];
[self.searchBar setDelegate:self];
[self.searchBar sizeToFit];
[self.tableView setTableHeaderView:self.searchBar];
self.searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
[self.searchDisplay setSearchResultsDataSource:self];
[self.searchDisplay setSearchResultsDelegate:self];
[self.searchDisplay setDelegate:self];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)myTableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
if (myTableView == self.tableView) {
return array.count;
}
else{
return arrayFiltrato.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (myTableView == self.tableView) {
cell.textLabel.text = [array objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [arrayFiltrato objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark -
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
[arrayFiltrato removeAllObjects];
// if ([scope isEqualToString:#"All"] || [product.type isEqualToString:scope]) {
for (NSString *str in array) {
NSLog(#"str: %# - scope: %#",str,scope);
if ([scope isEqualToString:str]) {
NSComparisonResult result = [str compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame) {
[arrayFiltrato addObject:str];
}
}
}
}
#pragma mark -
#pragma mark UIsearchDisplay Delegate Methods
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
NSLog(#"ok");
return YES;
}
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
NSLog(#"ok");
[self filterContentForSearchText:[self.searchDisplayController.searchBar text]
scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
- (void)searchDisplayDidBeginSearch:(UISearchDisplayController *)controller{
[self.searchDisplayController.searchResultsTableView setDelegate:self];
}
- (void)searchDisplayDidEndSearch:(UISearchDisplayController *)controller{
//[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
}
#pragma mark -
-(void)searchBar:(id)sender{
[self.searchDisplayController setActive:YES animated:YES];
}

The problem is that the delegate method is wrong, isn't this:
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldRelo....
but this:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldRelo...

Related

how to push tableview to UIView dynamically in iOS?

i am displaying list content in table view now i want when i click
one menu of list that menu content display in UIView on next screen
. how to push UITableView to UIView dynamically in iOS.
#import "SmsCategoryTitleTableViewController.h"
#import "CategoryMainWindowViewController.h"
#import "AppDelegate.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "SmsTitle.h"
#import "SMSCategory.h"
#import"smsDisplayViewController.h"
#interface SmsCategoryTitleTableViewController ()
#end
#implementation SmsCategoryTitleTableViewController
#synthesize theSearchBar,Id;
#synthesize theTableView;
#synthesize array;
#synthesize disableViewOverlay;
#synthesize Arrayobject;
- (void)viewDidLoad
{
[super viewDidLoad];
[self SearchBarCode];
[self GetTableData];
[self.tableView reloadData];
filteredContentList = [[NSMutableArray alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
// [self performSelector:#selector(push:) withObject:nil afterDelay:0.2f];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
-(void)GetTableData
{
array = [[NSMutableArray alloc] init];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDir = [docPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"SMS.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:self.databasePath];
[database setLogsErrors:TRUE];
[database open];
NSString *anQuery = [[NSString alloc]initWithFormat:#"SELECT * FROM SMSnJokes
where CategoryId=%#",self.Id];
FMResultSet *results = [database executeQuery:anQuery];
while([results next])
{
SmsTitle *title=[[SmsTitle alloc]init];
title.Id = [results stringForColumn:#"Id"];
title.CategoryId = [results stringForColumn:#"CategoryId"];
title.Title = [results stringForColumn:#"Title"];
[array addObject:title];
// NSLog(#"SMS LIST %#",title.Title);
}
[database close];
}
-(void)SearchBarCode
{
self.disableViewOverlay = [[UIView
alloc]initWithFrame:CGRectMake(0.0f,44.0f,320.0f,0)];
self.disableViewOverlay.backgroundColor=[UIColor lightGrayColor];
self.disableViewOverlay.alpha = 0;
theSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, 374.0f, 50)];
theSearchBar.delegate =self;
[self.tableView addSubview:theSearchBar];
self.navigationItem.title=#"SMS LIST";
[[self tableView] setTableHeaderView:theSearchBar];
}
- (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.
if (isSearching)
{
return [filteredContentList count];
}
else
{
return [array count];
}
}
- (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 (isSearching)
{
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else
{
SmsTitle *title = [array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%# ",[title
valueForKey:#"Title"]]];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)searchTableList
{
NSString *searchString =theSearchBar.text;
filteredContentList = [[NSMutableArray alloc]init];
[filteredContentList removeAllObjects];
for (SmsTitle *title in array)
{
NSString *tempStr = title.Title;
NSComparisonResult result = [tempStr compare:searchString options:
(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0,
[searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:title.Title];
}
}
}
#pragma mark - Search Implementation
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.theSearchBar resignFirstResponder];
}
- (void) dismissKeyboard
{
[self.theSearchBar becomeFirstResponder];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearching = YES;
[theSearchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
theSearchBar.text=nil;
[theSearchBar setShowsCancelButton:NO animated:YES];
[theSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[theSearchBar setShowsCancelButton: YES animated: YES];
[self searchTableList];
[searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active
{
self.theTableView.allowsSelection = !active;
self.theTableView.scrollEnabled = !active;
if (!active)
{
[disableViewOverlay removeFromSuperview];
[searchBar resignFirstResponder];
}
else
{
self.disableViewOverlay.alpha = 0;
[self.view addSubview:self.disableViewOverlay];
[UIView beginAnimations:#"FadeIn" context:nil];
[UIView setAnimationDuration:0.5];
self.disableViewOverlay.alpha = 0.6;
[UIView commitAnimations];
NSIndexPath *selected = [self.theTableView indexPathForSelectedRow];
if (selected)
{
[self.theTableView deselectRowAtIndexPath:selected
animated:NO];
}
}
[searchBar setShowsCancelButton:active animated:YES];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
[self.theSearchBar resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
textField.returnKeyType=UIReturnKeyDefault ;
return[textField resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc]
init];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Ok got your point. I think you want to pass data of selected cell to
next UIViewController. Assume, you want to pass cell title label and
you have an array of objects. In yoursmsDisplayViewController.h
#import <UIKit/UIKit.h>
#interface smsDisplayViewController : UIViewController
#property (strong, nonatomic) NSString *cellName;
Now in your SmsCategoryTitleTableViewController.m you have
NSMutableArray *nameList;
Then in your table view delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [self.storyboard instantiateViewControllerWithIdentifier:#"LoginIdentifier"];
viewController1.cellName=[nameList objectAtIndex:indexPath.row];
[self.navigationController pushViewController:viewController1 animated:YES];
}
UPDATE This is the code you posted first in your question.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [[smsDisplayViewController
alloc] initWithNibName:#"viewController1" bundle:nil];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Now the wrong thing you are doing here
isinitWithNibName:#"viewController1". If you are not using any nib
file then your code should be
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc] init];
[self.navigationController pushViewController:viewController1 animated:YES];
You can use Accessory Buttons in UITableView or learn more about segues.
You have to use prepareForSegue: to pass data to another ViewController.
You can learn it from Here which teaches you how to transfer data between ViewControllers while using Segue.

Search textfield Results not selectable

I'm using UITextFields as my search bars. I had to do this because I have multiple inputs for people to search for. The search is working perfectly. In fact the text field is working better than a normal search bar memory wise. The only problem is that I cannot select the resulting cell. When I press the cell nothing at all happens. I even put a log statement in didselect and the cell is not even getting the action. Help please.
- (void)viewDidLoad
{
[super viewDidLoad];
self.ASearch.delegate = self;
self.BSearch.delegate = self;
NSAttributedString *str = [[NSAttributedString alloc] initWithString:#"Location" attributes:#{ NSForegroundColorAttributeName : [UIColor blueColor] }];
self.ASearch.attributedPlaceholder = str;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
-(void)viewWillDisappear:(BOOL)animated {
[self dismissKeyboard];
[super viewWillDisappear:animated];
}
-(void)dismissKeyboard {
[ASearch resignFirstResponder];
[BSearch resignFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[Asearch becomeFirstResponder];
}
- (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;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (searchArray.count == 0) {
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
messageLabel.text = #"Search!";
messageLabel.textColor = [UIColor redColor];
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.font = [UIFont fontWithName:#"TimesNewRomanPS-BoldMT" size:20];
[messageLabel sizeToFit];
self.tableView.backgroundView = messageLabel;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
return 0;
} else {
self.tableView.backgroundView = nil;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return searchArray.count;
}
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
headerView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 90.0, 320.0, 90.0)];
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"searchCell";
TopCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
PFObject *searchObject = [searchArray objectAtIndex:indexPath.row];
cell.AImage.image = [UIImage imageNamed:#"DefaultThumbnail"];
cell.AImage.layer.cornerRadius = 5.0f;
cell.AImage.clipsToBounds = YES;
cell.AName.text = [searchObject objectForKey:#"name"];
cell.addressLabel.text = [NSString stringWithFormat:#"%#, %#, %#",[searchObject objectForKey:#"address"],[searchObject objectForKey:#"city"], [searchObject objectForKey:#"state"]];
cell.placeType.text = [searchObject objectForKey:#"name"];
return cell;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == ASearch) {
NSString *searchString = [NSString stringWithString:placeSearch.text];
searchString = [searchString stringByReplacingCharactersInRange:range withString:string];
[self searchDataBase:searchString];
return YES;
} else {
return NO;
}
}
-(void)searchDataBase: (NSString *)subString {
PFQuery *query = [PFQuery queryWithClassName:#"HotSpots"];
[query whereKey:#"name" matchesRegex:subString modifiers:#"i"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
searchArray = [NSArray arrayWithArray:objects];
[self.tableView reloadData];
NSLog(#"%lu", objects.count);
}];
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
[self dismissKeyboard];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[self searchDataBase:textField.text];
[ASearch resignFirstResponder];
[BSearch resignFirstResponder];
[self dismissKeyboard];
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier]isEqualToString:#"Segue"]) {
NSIndexPath *indexpath = [self.tableView indexPathForSelectedRow];
HSBarTableViewController *Controller = (HSBarTableViewController *)[segue destinationViewController];
PFObject *pObject = [searchArray objectAtIndex:indexpath.row];
Controller.arObject = pObject;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"Segue" sender:self];
NSLog(#"Pressed");
}

How to keep text in search bar when dismiss UISearchDisplayController

I'm using a UISearchDisplayController in my app. When the user selects an item in the search results returned I deactivate the UISearchDisplayController. Deactivating the controller clears the text the user has typed. I want to keep it there. I try to assign the text back into the UISearchBar by setting it again after the controller has been deactivated. The text does appear in the search bar but this will cause the UISearchDisplayController to active again even though I have disable the delegate! This issue only happens on iOS 7. Before iOS7, the code below works charmingly.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = [indexPath row];
NSString *term = [keywordSuggestion objectAtIndex:row];
[search resignFirstResponder];
[self handleSearchForTerm:term];
}
-(void)handleSearchForTerm:(NSString *)searchTerm {
[searchDisplayController setActive:NO animated:YES]; //searchbar text will be lost
searchDisplayController.delegate = nil;
search.text = term;
searchDisplayController.delegate = self;
}
Is there are a way that I can set the text of the UISearchBar without having the UISearchDisplayController that's associated with become active?
Here is an example of some working code:
#import "RBTableViewController.h"
#interface RBTableViewController () <UISearchDisplayDelegate>
#end
#implementation RBTableViewController {
UISearchBar *_searchBar;
UISearchDisplayController *_searchController;
NSMutableArray *_searchResults;
NSMutableArray *_model;
NSString *_cachedSearchTerm;
}
- (NSMutableArray *)currentModel {
return _searchController.isActive ? _searchResults : _model;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_searchResults = [[NSMutableArray alloc] init];
_model = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[_model addObject:[NSString stringWithFormat:#"item %d", i]];
}
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
_searchController.searchResultsDataSource = self;
_searchController.searchResultsDelegate = self;
_searchController.delegate = self;
[_searchController.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
self.tableView.tableHeaderView = _searchBar;
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
controller.searchBar.text = _cachedSearchTerm;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == _searchController.searchResultsTableView) {
_cachedSearchTerm = _searchBar.text;
[_searchController setActive:NO animated:YES];
[self filterResults:_cachedSearchTerm];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self currentModel] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.text = [self currentModel][indexPath.row];
return cell;
}
- (void)filterResults:(NSString *)searchTerm {
[_searchResults removeAllObjects];
[_searchResults addObjectsFromArray:[_model filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF contains[s] %#", searchTerm]]];
[_searchController.searchResultsTableView reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
if (_cachedSearchTerm) {
controller.searchBar.text = _cachedSearchTerm;
}
}
#end

Working with UISearchBar Filterable TableView

I am pretty new in objective c so hopefully this all make sense.I have followed this video tutorial from YouTube.The program is not working .
You can download the project from this link.Guide me
to make this program functional.
use the following tutorial is the simple way to get the answer and and also u get the sample code in github, the link is http://www.appcoda.com/how-to-add-search-bar-uitableview/
in your view controller.h file
import
#interface RecipeBookViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
NSArray *recipes; //this is used for load the data to table
NSArray *searchResults; //this is used for search the particular name in uitableview
}
#property (nonatomic, strong) UITableView *tableView; //progrmatically allocationg the tableview
.m file
#synthesize tableView; //this is used accessing the name in more than one time
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
searchResults=[NSArray alloc]init];
recipes = [NSArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto", #"Full Breakfast", #"Hamburger", #"Green Tea", #"Thai Shrimp Cake", #"Angry Birds Cake", #"Ham and Cheese Panini", nil];
//create the tableview
tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 163, 320, 317)];
tableView.delegate=self;
tableView.dataSource=self;
[self. tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview: tableView];
}
//this is for loading the table data
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [recipes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
}
return cell;
}
//this is for search bar delegate method for filtering
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex: [self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
finally add the one search bar display controller only in top on the view
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar; // called when text starts editing
{
if (searching)
{
searching=YES;
letsUserSelectRow=YES;
}
else
{
searching=NO;
letsUserSelectRow=YES;
}
// self.tbl_searchtable.scrollEnabled=NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
searching = NO;
letsUserSelectRow = YES;
searchBar.text = #"";
[searchBar resignFirstResponder];
[self.tbl_searchuser reloadData];
}
-(NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(letsUserSelectRow)
return indexPath;
else
return nil;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; // called when text changes (including clear)
{
_tbl_searchuser.hidden=FALSE;
[copylistofitem removeAllObjects];
if([searchText length] > 0)
{
searching = YES;
letsUserSelectRow = YES;
self.tbl_searchuser.scrollEnabled = YES;
[self searchtableview];
}
else
{
searching = NO;
letsUserSelectRow= NO;
[_searchbar resignFirstResponder];
//self.tbl_searchtable.scrollEnabled = NO;
}
[copylistofitem retain];
[self.tbl_searchuser reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar; // called when keyboard search button pressed
{
[self hide];
//[self searchtableview];
}
-(void)searchtableview
{
_tbl_searchuser.frame=CGRectMake(0, 65, 320, 140);
NSString *searchText = _searchbar.text;
NSLog(#"%#",array_allusers);
for(int l = 0; l < [array_allusers count]; l++)
{
NSString *tempstr = [[array_allusers objectAtIndex:l] objectForKey:#"username"];
NSRange rngstr = [tempstr rangeOfString:searchText options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if(rngstr.length > 0)
{
[copylistofitem addObject:[array_allusers objectAtIndex:l]];
[copylistofitem retain];
}
}
NSLog(#"%#",copylistofitem);
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"username" ascending:YES];
[copylistofitem sortUsingDescriptors:[NSArray arrayWithObject:sort]];
[_tbl_searchuser reloadData];
}
-(void)hide
{
[_searchbar resignFirstResponder];
_tbl_searchuser.frame=CGRectMake(0, 65, 320, 274);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (searching && [_searchbar.text length] > 0)
return [copylistofitem count];
else
return yourarray;
}
NSMutableArray *copylistofitem;
BOOL searching;
BOOL letsUserSelectRow;

setEditing method causing SIGABRT

I'm working form the big nerd ranch book, iphone programming. I'm working through Chapt 11 where you implement your own setEditing method:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
if( editing) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
}
else {
/*
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
*/
}
}
When I run this the whole app does a Sigabort without any info other than that. The line that seems to cause the problem is this one:
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
I'm not sure what I'm doing wrong. What else would be good to see?
This is the whole file:
//
// TeamsViewController.m
// TeamTrackerClient
//
// Created by Mark Steudel on 3/4/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "TeamsViewController.h"
#import "Team.h"
#implementation TeamsViewController
-(id) init
{
self = [super initWithStyle:UITableViewStyleGrouped];
teams = [[NSMutableArray alloc] init];
Team *team = [[Team alloc] init];
team.teamName = [NSString stringWithFormat: #"Fighting Axons"];
team.teamCode = [NSString stringWithFormat: #"FA1"];
[teams addObject:team];
Team *team2 = [[Team alloc] init];
team2.teamName = [NSString stringWithFormat: #"Pipers Peddlers"];
team2.teamCode = [NSString stringWithFormat: #"PP1"];
[teams addObject:team2];
return self;
}
- (id) initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (UIView *) headerView
{
if( headerView)
return headerView;
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[editButton setTitle: #"Edit" forState: UIControlStateNormal];
float w = [[UIScreen mainScreen] bounds].size.width;
CGRect editButtonFrame = CGRectMake(8.0, 8.0, w - 16.0, 30.0);
[editButton setFrame:editButtonFrame];
[editButton addTarget:self
action:#selector(editingButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
CGRect headerViewFrame = CGRectMake(0, 0, w, 48);
headerView = [[UIView alloc] initWithFrame:headerViewFrame];
[headerView addSubview:editButton];
return headerView;
}
- (void) editingButtonPressed: (id) sender
{
if( [self isEditing] ) {
[sender setTitle:#"Edit" forState:UIControlStateNormal];
[self setEditing:NO animated:YES];
}
else {
[sender setTitle: #"Done" forState:UIControlStateNormal];
[self setEditing:YES animated:YES];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
return [self headerView];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return [[self headerView] frame].size.height;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
Team *t = [teams objectAtIndex:[sourceIndexPath row]];
[teams removeObjectAtIndex:[sourceIndexPath row]];
[teams insertObject:t atIndex:[destinationIndexPath row]];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if( editingStyle == UITableViewCellEditingStyleDelete ) {
[teams removeObjectAtIndex:[indexPath row]];
[tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade];
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
if( editing) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
}
else {
/*
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
*/
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int numberOfRows = [teams count];
if( [self isEditing] )
numberOfRows++;
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if( !cell ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
}
if( [indexPath row] < [teams count] ) {
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
}
else {
[[cell textLabel] setText: #"Add New Item ... "];
}
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
return cell;
}
#end
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
this make the table view reload data ..and check the data in its datasource methods..
i believe it is crashing on
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
there might be no objects in the teams array on here for the new index paths...
check by breakpointing here..

Resources