I am trying to add a search bar to my existing table view...
I have added my searchBar property to my .m file and I have added the searchbar delegate and yet I have no avail. I am new to adding search functions to my code.
here is my header
#import
#import "SelectSingleView.h"
#import "SelectMultipleView.h"
#import "AddressBookView.h"
#import "FacebookFriendsView.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------
#interface PeopleView : UITableViewController <SelectSingleDelegate, SelectMultipleDelegate, AddressBookDelegate, FacebookFriendsDelegate>
//-------------------------------------------------------------------------------------------------------------------------------------------------
#property (nonatomic, assign) IBOutlet id<PeopleView>delegate;
#end
and here is the .m file
#import <Parse/Parse.h>
#import "ProgressHUD.h"
#import "utilities.h"
#import "PeopleView.h"
#import "ProfileView.h"
#import "SelectSingleView.h"
#import "SelectMultipleView.h"
#import "AddressBookView.h"
#import "FacebookFriendsView.h"
#import "NavigationController.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------
#interface PeopleView()
{
BOOL skipLoading;
NSMutableArray *users;
NSMutableArray *userIds;
NSMutableArray *sections;
}
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#end
//-------------------------------------------------------------------------------------------------------------------------------------------------
#implementation PeopleView
//#synthesize delegate;
#synthesize searchBar;
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
{
[self.tabBarItem setImage:[UIImage imageNamed:#"tab_people"]];
self.tabBarItem.title = #"People";
//-----------------------------------------------------------------------------------------------------------------------------------------
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(actionCleanup) name:NOTIFICATION_USER_LOGGED_OUT object:nil];
}
return self;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidLoad
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[super viewDidLoad];
self.title = #"Friends";
self.navigationController.navigationBar.tintColor= [UIColor colorWithRed:(255/256.0) green:(128/256.0) blue:(0/256.0) alpha:(1.0)];
//---------------------------------------------------------------------------------------------------------------------------------------------
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
action:#selector(actionAdd)];
//---------------------------------------------------------------------------------------------------------------------------------------------
self.tableView.tableFooterView = [[UIView alloc] init];
//---------------------------------------------------------------------------------------------------------------------------------------------
users = [[NSMutableArray alloc] init];
userIds = [[NSMutableArray alloc] init];
// UIButton *facebookButton = [UIButton buttonWithType:UIButtonTypeSystem];
//[facebookButton setBackgroundImage:[[UIImage imageNamed:#"gibrlogo.png"];
//[facebookButton setTitle:#"Facebook Friends" forState:UIControlStateNormal];
// [facebookButton sizeToFit];
//facebookButton.center = CGPointMake(210.0, 30.0);// for center;
// Add an action in current code file (i.e. target)
//[facebookButton addTarget:self action:#selector(facebookButtonPressed:)
// forControlEvents:UIControlEventTouchUpInside];
//[self.view addSubview:facebookButton];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)viewDidAppear:(BOOL)animated
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[super viewDidAppear:animated];
//---------------------------------------------------------------------------------------------------------------------------------------------
if ([PFUser currentUser] != nil)
{
if (skipLoading) skipLoading = NO; else [self loadPeople];
}
else LoginUser(self);
}
#pragma mark - Backend methods
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)facebookButtonPressed:(UIButton *)facebookButton
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
FacebookFriendsView *facebookFriendsView = [[FacebookFriendsView alloc] init];
facebookFriendsView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:facebookFriendsView];
[self presentViewController:navController animated:YES completion:nil];
NSLog(#"facebookButton Pressed");
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)loadPeople
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
PFQuery *query = [PFQuery queryWithClassName:PF_PEOPLE_CLASS_NAME];
[query whereKey:PF_PEOPLE_USER1 equalTo:[PFUser currentUser]];
[query includeKey:PF_PEOPLE_USER2];
[query setLimit:1000];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
{
if (error == nil)
{
[users removeAllObjects];
[userIds removeAllObjects];
for (PFObject *people in objects)
{
PFUser *user = people[PF_PEOPLE_USER2];
[users addObject:user];
[userIds addObject:user.objectId];
}
[self setObjects:users];
[self.tableView reloadData];
}
else [ProgressHUD showError:#"Network error."];
}];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchUsers:(NSString *)search_lower
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
PFQuery *query1 = [PFQuery queryWithClassName:PF_BLOCKED_CLASS_NAME];
[query1 whereKey:PF_BLOCKED_USER1 equalTo:[PFUser currentUser]];
PFQuery *query2 = [PFQuery queryWithClassName:PF_USER_CLASS_NAME];
[query2 whereKey:PF_USER_OBJECTID notEqualTo:[PFUser currentId]];
[query2 whereKey:PF_USER_OBJECTID doesNotMatchKey:PF_BLOCKED_USERID2 inQuery:query1];
[query2 whereKey:PF_USER_FULLNAME_LOWER containsString:search_lower];
[query2 orderByAscending:PF_USER_FULLNAME_LOWER];
[query2 setLimit:1000];
[query2 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
{
if (error == nil)
{
[users removeAllObjects];
[users addObjectsFromArray:objects];
[self.tableView reloadData];
}
else [ProgressHUD showError:#"Network error."];
}];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)setObjects:(NSArray *)objects
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if (sections != nil) [sections removeAllObjects];
//---------------------------------------------------------------------------------------------------------------------------------------------
NSInteger sectionTitlesCount = [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];
sections = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//---------------------------------------------------------------------------------------------------------------------------------------------
for (NSUInteger i=0; i<sectionTitlesCount; i++)
{
[sections addObject:[NSMutableArray array]];
}
//---------------------------------------------------------------------------------------------------------------------------------------------
NSArray *sorted = [objects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
PFUser *user1 = (PFUser *)obj1;
PFUser *user2 = (PFUser *)obj2;
return [user1[PF_USER_FULLNAME] compare:user2[PF_USER_FULLNAME]];
}];
//---------------------------------------------------------------------------------------------------------------------------------------------
for (PFUser *object in sorted)
{
NSInteger section = [[UILocalizedIndexedCollation currentCollation] sectionForObject:object collationStringSelector:#selector(fullname)];
[sections[section] addObject:object];
}
}
#pragma mark - User actions
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionCleanup
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[users removeAllObjects];
[userIds removeAllObjects];
[sections removeAllObjects];
[self.tableView reloadData];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionAdd
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:#"Search for a Friend" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionSelectSingle]; }];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:#"Add Friends" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionSelectMultiple]; }];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:#"Invite Friends SMS" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionAddressBook]; }];
UIAlertAction *action4 = [UIAlertAction actionWithTitle:#"Invite Facebook Friends" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { [self actionFacebookFriends]; }];
UIAlertAction *action5 = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:action1]; [alert addAction:action2]; [alert addAction:action3]; [alert addAction:action4]; [alert addAction:action5];
[self presentViewController:alert animated:YES completion:nil];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionSelectSingle
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
SelectSingleView *selectSingleView = [[SelectSingleView alloc] init];
selectSingleView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:selectSingleView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - SelectSingleDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectSingleUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionSelectMultiple
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
SelectMultipleView *selectMultipleView = [[SelectMultipleView alloc] init];
selectMultipleView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:selectMultipleView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - SelectMultipleDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectMultipleUsers:(NSMutableArray *)users_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
for (PFUser *user in users_)
{
[self addUser:user];
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionAddressBook
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
AddressBookView *addressBookView = [[AddressBookView alloc] init];
addressBookView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:addressBookView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - AddressBookDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectAddressBookUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)actionFacebookFriends
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
skipLoading = YES;
FacebookFriendsView *facebookFriendsView = [[FacebookFriendsView alloc] init];
facebookFriendsView.delegate = self;
NavigationController *navController = [[NavigationController alloc] initWithRootViewController:facebookFriendsView];
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - FacebookFriendsDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)didSelectFacebookUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self addUser:user];
}
#pragma mark - Helper methods
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)addUser:(PFUser *)user
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([userIds containsObject:user.objectId] == NO)
{
PeopleSave([PFUser currentUser], user);
[users addObject:user];
[userIds addObject:user.objectId];
[self setObjects:users];
[self.tableView reloadData];
}
}
#pragma mark - Table view data source
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [sections count];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [sections[section] count];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([sections[section] count] != 0)
{
return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
}
else return nil;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
cell.textLabel.text = user[PF_USER_FULLNAME];
cell.detailTextLabel.text = user[PF_USER_EMAIL];
if(cell.detailTextLabel.text == nil){
cell.detailTextLabel.text = #"Facebook Account";
}
return cell;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
return YES;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
//---------------------------------------------------------------------------------------------------------------------------------------------
PeopleDelete([PFUser currentUser], user);
//---------------------------------------------------------------------------------------------------------------------------------------------
[users removeObject:user];
[userIds removeObject:user.objectId];
[self setObjects:users];
//---------------------------------------------------------------------------------------------------------------------------------------------
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark - Table view delegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//---------------------------------------------------------------------------------------------------------------------------------------------
NSMutableArray *userstemp = sections[indexPath.section];
PFUser *user = userstemp[indexPath.row];
//---------------------------------------------------------------------------------------------------------------------------------------------
ProfileView *profileView = [[ProfileView alloc] initWith:nil User:user];
profileView.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:profileView animated:YES];
}
#pragma mark - UISearchBarDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
if ([searchText length] > 0)
{
[self searchUsers:[searchText lowercaseString]];
}
else [self loadPeople];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ setShowsCancelButton:YES animated:YES];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ setShowsCancelButton:NO animated:YES];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[self searchBarCancelled];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar_
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
[searchBar_ resignFirstResponder];
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
- (void)searchBarCancelled
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
searchBar.text = #"";
[searchBar resignFirstResponder];
[self loadPeople];
}
#end
Related
I have been stuck on this all day and I'm looking for some help. I am making an app where someone can type in a web address that web address will be stored in a table view. When the user taps on that cell it will take them to the web view where they can view that site. I am using parse as my backend to store the user input. ( I am not using PFQueryTableView)
Here is my code for the tableViewController:
interface MenuTableViewController : UITableViewController
#property(strong, nonatomic) NSMutableArray *referralArray;
#property (strong, nonatomic) PFObject *selectLink;
#property (nonatomic, strong) NSArray *webInput;
#property (nonatomic, strong) UIRefreshControl *refreshControl;
#end
#interface MenuTableViewController ()
#end
#implementation MenuTableViewController
#synthesize referralArray;
- (void)viewDidLoad
{
[super viewDidLoad];
PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
NSLog(#"Current user: %#", currentUser.username);
}
else {
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
//refresh inbox
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(retrieveMessages) forControlEvents:UIControlEventValueChanged];
//swipe to delete
self.tableView.allowsMultipleSelectionDuringEditing = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setHidden:NO];
}
#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.webInput count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"refCell"forIndexPath:indexPath];
PFObject *web = [self.webInput objectAtIndex:indexPath.row];
cell.textLabel.text = [web objectForKey:#"RefLink"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectLink = [self.webInput objectAtIndex:indexPath.row];
//NSString *fileType = [self.selectLink objectForKey:#"RefLink"];
//[self performSegueWithIdentifier:#"webSegue" sender:self];
NSDictionary *dict = [self.webInput objectAtIndex:indexPath.section];
NSString *link=[dict valueForKey:#"link"];
//Create a URL object.
NSURL *url = [NSURL URLWithString:link];
UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
WebViewController *web = (WebViewController *)nav.topViewController;
web.webLink =url;
}
//swipe to delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//try this
PFObject *object = [self.webInput objectAtIndex:indexPath.row];
[object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self refreshControl];
[self.tableView reloadData];
}];
}
}
#pragma mark - Helper methods
- (void)retrieveMessages {
PFQuery *query = [PFQuery queryWithClassName:#"Referrals"];
//[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
//run the query here for messages
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// We found messages!
self.webInput = objects;
[self.tableView reloadData];
NSLog(#"Retrieved %lu messages", (unsigned long)[self.webInput count]);
}
if ([self.refreshControl isRefreshing]) {
[self.refreshControl endRefreshing];
}
}];
}
#pragma mark - LogOut
- (IBAction)logout:(id)sender {
[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showLogin"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
else if ([segue.identifier isEqualToString:#"webSegue"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
WebViewController *webView = (WebViewController *)segue.destinationViewController;
webView.webAddress = self.selectLink;
}
}
#end
If Someone could help me out I would greatly appreciate it!
I am adding search bar to an app based on the Todo parse.com tutorial app. The search is working, but when I delete the search term, the app crashes. So for example, I type in an acronym "ABC" and it returns the values fine with a searchm as I delete "ABC" the app crashes with an out of bounds error.
#import "MyTableController.h"
#interface MyTableController() <UISearchDisplayDelegate> {
}
#property (nonatomic, strong) UISearchBar *searchBar;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
#implementation MyTableController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
self.className = #"Jargon";
self.keyToDisplay = #"acronym";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 2;
}
return self;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar
contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height);
self.tableView.contentOffset = offset;
self.searchResults = [NSMutableArray array];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName: self.className];
[query whereKey:#"acronym" containsString:searchTerm];
NSArray *results = [query findObjects:nil];
[self.searchResults addObjectsFromArray:results];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count ;
} else {
return self.searchResults.count +1;
}
}
#pragma mark - Parse
- (void)objectsDidLoad:(NSError *)error {
[super objectsDidLoad:error];
}
- (void)objectsWillLoad {
[super objectsWillLoad];
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.className];
if ([self.objects count] == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByAscending:#"acronym"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [object objectForKey:#"acronym"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Term: %#", [object objectForKey:#"text"]];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
}
#end
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.
This was working fine yesterday and without touching anything it stopped working today. When I run the query to allocate my 'filterEvents' array, 'objects' in the block is empty. Anyone know what's going on?
#import "FilterViewController.h"
#interface FilterViewController ()
#end
#implementation FilterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.filterTable.dataSource = self;
self.filterTable.delegate = self;
[self performSelector:#selector(retrieveFilteredEvents)];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.filterEvents count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"filterTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
self.eventTitle = [tempDict objectForKey:#"eventType"];
cell.textLabel.text = self.eventTitle;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
NSString *string = [tempDict objectForKey:#"eventType"];
[self.delegate setFilter:string];
[self dismissViewControllerAnimated:YES completion:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateParent" object:nil];
}
#pragma mark - Helper Methods
- (IBAction)done:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)retrieveFilteredEvents
{
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"eventTypes"];
[retrieveEvents orderByAscending:#"eventOrder"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.filterEvents = [[NSArray alloc] initWithArray:objects];
NSLog(#"%#", self.filterEvents);
}
[self.filterTable reloadData];
}];
}
#end
Heres a few photos to get started:
This is what I CURRENTLY have for the main view:
Then when the user selects the UISearchBar, this is what happens:
Instead of the second photo, I would like the view to change to this:
Here is the code so far:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
/*
self.searchView = [[UserSearchView alloc] initWithFrame:self.view.frame];
self.searchView.searchResults.delegate = self;
self.searchView.searchResults.dataSource = self;
[self.view addSubview:self.searchView];
*/
self.mainTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
[self.mainTableView setDelegate:self];
[self.mainTableView setDataSource:self];
[self.mainTableView setShowsHorizontalScrollIndicator:NO];
[self.mainTableView setShowsVerticalScrollIndicator:NO];
[self.view addSubview:self.mainTableView];
self.searchBar = [[UISearchBar alloc] init];
[self.searchBar setBarStyle:UIBarStyleBlackTranslucent];
[self.searchBar setAutocorrectionType:UITextAutocorrectionTypeNo];
[self.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
self.searchCon = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
[self.searchCon setDelegate:self];
[self.searchCon setSearchResultsDataSource:self];
[self.searchCon setSearchResultsDelegate:self];
self.navigationItem.titleView = self.searchCon.searchBar;
/* This generates the result I want but I do not want the search
* bar in the tableviews header, but rather in the uinavigationcontroller's
* uinavigationbar.
*/
//self.mainTableView.tableHeaderView = self.searchBar;
[self.view setBackgroundColor:[UIColor whiteColor]];
}
#pragma mark -
#pragma mark - UISearchDisplayController Delegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
if ([searchString isEqualToString:#""])
return NO;
PFQuery *query = [PFUser query];
[query whereKey:#"username" containsString:searchString];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.array = [NSMutableArray arrayWithArray:objects];
[self.searchDisplayController.searchResultsTableView reloadData];
[self.mainTableView reloadData];
} else {
[[[UIAlertView alloc] initWithTitle:#"Failed Search" message:[NSString stringWithFormat:#"%#", [error userInfo]] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
}];
return YES;
}
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
[controller.searchBar setShowsCancelButton:YES animated:YES];
NSLog(#"%#", controller);
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[controller.searchBar setShowsCancelButton:NO animated:YES];
NSLog(#"%#", controller);
}
#pragma mark -
#pragma mark - UITableView Delegate & Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
[cell.textLabel setText:[[self.array objectAtIndex:[indexPath row]] objectForKey:#"username"]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ProfileViewController *profile = [[ProfileViewController alloc] init];
[profile setProfileUser:[self.array objectAtIndex:[indexPath row]]];
[self.navigationController pushViewController:profile animated:YES];
}
I am kinda lost on how to make the destination view work. Viewing the Facebook application is something I would like to reproduce, the way their search bars are implemented.
In addition, I'm using the PARSE framework. So a lot of the data being populated into the tableview is abstracted from the code.
Try this...
In your .h file
#interface YourtViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>
#property (nonatomic,strong) UISearchDisplayController* searchDisplayController;
#property (weak, nonatomic) IBOutlet UISearchBar *mySearchBar; //connect this IBOutlet to your serach bar in your storyboard or xib.
In your viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
self.mySearchBar.delegate=self;
self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.mySearchBar contentsController:self];
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
// do your additional code here
//
}
Now implement delegate methods of searchDisplayController.