I want to use SearchBar where the elements are generated dynamically with the help of service. Like, if I will pass "i" as parameter, service will fetch all the elements which includes "i" as initial characters. I cannot retrieve the logic as how to implement that in code.
Below is the service am using to get data. But I don't know how to implement Search bar using it.
NSURL * url=[NSURL URLWithString:#"http://dealnxt.com/api/search?searchkey=i"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Array is:%#",array);
Below i the code I tried :
.h file
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
}
#property (strong, nonatomic) IBOutlet UIView *SearchView;
#property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
#property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
#property (strong, nonatomic) IBOutlet UITableView *Content;
#end
.m file
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
return [filteredContentList count];
}
else {
return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:#"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:#"http://dealnxt.com/api/search?searchkey=%#",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:#"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:#"ProductDescriptionModel"];
[filteredContentList addObject:[[contentList firstObject] valueForKey:#"shortdescription"]];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = 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;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
Here is the solution :
.h file
#import
#interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
}
#property (strong, nonatomic) IBOutlet UIView *SearchView;
#property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
#property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
#property (strong, nonatomic) IBOutlet UITableView *Content;
#end
.m file
#import "SearchViewController.h"
#import "UIColor+HexString.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
- (void)viewDidLoad {
[super viewDidLoad];
_SearchView.backgroundColor=[UIColor colorWithHexString:#"#5130F7"];
_SearchBar.barTintColor=[UIColor colorWithHexString:#"#5130F7"];
_SearchBar.layer.borderWidth = 1;
_SearchBar.layer.borderColor = [UIColor colorWithHexString:#"#5130F7"].CGColor;
_Content.delegate=self;
_Content.dataSource=self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
return [filteredContentList count];
}
else {
return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:#"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:#"http://abc.in/key?key=%#",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:#"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:#"ProductDescriptionModel"];
filteredContentList =[contentList valueForKey:#"shortdescription"];
NSLog(#"filter:%#",filteredContentList);
[_Content reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
#end
Easy way to search anything from dynamic array
your controller.m
{
NSMutableArray *contacts;
NSMutableArray *combinearray;
NSString *searchTextString;
NSMutableArray *searchArray;
BOOL isFilter;
}
- (void)viewDidLoad {
[super viewDidLoad];
txtSearchBar.backgroundColor=Clear;
txtSearchBar.layer.cornerRadius=2;
txtSearchBar.clipsToBounds=YES;
txtSearchBar.delegate =self;
txtSearchBar.layer.borderColor=Black.CGColor;
txtSearchBar.layer.borderWidth=2.0f;
[txtSearchBar addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
txtSearchBar.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if(isFilter)
{
return [searchArray count];
}
else
return arrCardsName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFilter)
{
yourDictionary = [searchArray objectAtIndex:indexPath.row];
}
else
{
yourDictionary = [yourArray objectAtIndex:indexPath.row];
}
return cell;
}
-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if (searchText.length > 0)
{
isFilter=YES;
searchArray = [NSMutableArray array];
searchText = [NSString stringWithFormat:#"%#",searchText];
for ( NSDictionary* item in yourArray )
{
//NSLog(#"contacts ----->%#",[item objectForKey:#"city"]);
if ([[[item objectForKey:#"city"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound)//object for key #"do whatever you want to search"
{
[searchArray addObject:item];
}
}
}
if (!searchText || searchText.length == 0)
{
isFilter=NO;
searchArray = [yourArray mutableCopy];
}
else
{
if ([searchArray count] == 0)
{
NSLog(#"No data From Search");
}
}
// NSLog(#"search array ====>%#",searchArray);
[tbleView reloadData];
}
Related
I'm stumped. For some reason, when I tap my tableView cell, didSelectRowAtIndexPath is not executing? And yes, my tableView delegate is set, and data is populated in the cell label. Am I missing something obvious from my below? Essentially, when my user taps the tableView cell, the contents of the cell label should appear in a textfield.
.h
#interface RegisterViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate> {
}
#property (nonatomic) IBOutlet UITableView *tableView;
#end
.m
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.hidden = NO;
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (void)LoadJson_search{
searchArray=[[NSMutableArray alloc]init];
// NSLog(#"str......%#",strSearch);
// This API key is from https://developers.google.com/maps/web/
NSString *str1 = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyAm7buitimhMgE1dKV2j4_7doULluiiDzU", strSearch];
NSURL *url = [NSURL URLWithString:str1];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error=nil;
if(data.length==0)
{
}
else
{
NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"1,,,,%#",jsondic);
[searchArray removeAllObjects];
if([[jsondic objectForKey:#"status"]isEqualToString:#"ZERO_RESULTS"])
{
}
else if([[jsondic objectForKey:#"status"]isEqualToString:#"INVALID_REQUEST"])
{
}
else
{
for(int i=0;i<[jsondic.allKeys count];i++)
{
NSString *str1=[[[jsondic objectForKey:#"predictions"] objectAtIndex:i] objectForKey:#"description"];
[searchArray addObject:str1];
}
self.tableView.hidden = NO;
// NSLog(#"%#", searchArray);
}
if (searchArray.count == 0) {
self.tableView.hidden = YES;
}else{
[self.tableView reloadData];
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// if (self.addressField.tag == 3) {
if (textField == self.addressField) {
strSearch = [self.addressField.text stringByReplacingCharactersInRange:range withString:string];
if([string isEqualToString:#" "]){
}else{
[self LoadJson_search];
}}
// }
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
self.tableView.hidden = YES;
[self.tableView reloadData];
return YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return searchArray.count;
}
-(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"cell"];
if(!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"TAPPED CELL");
self.addressField.text = [searchArray objectAtIndex:indexPath.row];
self.tableView.hidden = YES;
[self.tableView reloadData];
}
Try with the next line in your viewDidLoad:
self.tableView.allowsSelection = YES;
Or check that property in your storyboard. Well you can try with the cell too like this:
// This line do not affect the selection delegate only the style
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = YES;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i have following code in viewdidload
totalstring=[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"n",#"o",#"p",#"q",#"r",#"s",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z", nil];
indid=indidvalue1;
NSLog(#"the ind id value is %#",indid);
serviceCall=[[Services alloc]init];
NSString *contactsDisplay1=#"ContactDetails";
NSDictionary *contactsDisplayDetails1 =#{#"IND_ID":indid};
[serviceCall ContactsDisplayUrl:contactsDisplay1 ContactsDisplayDetails:contactsDisplayDetails1];
[serviceCall setDelegate:self];
code for implimenting search bar
{
filteredstring =[[NSMutableArray alloc]init];
for (NSString *str in totalstring )
{
NSRange stringrange =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringrange.location!= NSNotFound)
{
[filteredstring addObject:str];
}
}
}
[tableView reloadData];
code for table view
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [searchResultsArray objectAtIndex:indexPath.row];
} else
{
UIFont *myfont=[UIFont fontWithName:#"Arial" size:35];
cell.textLabel.text = [contactNameSplitDisplayArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[relationTypeSplitDisplayArray objectAtIndex:indexPath.row];
cell.textLabel.font=myfont;
}
return cell;
How can i implement search bar in table view for contacts in story board ?I am new to iOS
?
and how to implement plus button and dots button within the table view?
Devi my complete answer.It works perfectly.I use search bar.Also use that delegate methods.
ViewController.h
#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h> //Must import contact framework
#interface ViewController : UIViewController<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchbarContacts;
#property (strong, nonatomic) IBOutlet UITableView *tableViewContactData;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayTableData;
NSMutableArray *arraySearchContactData;
}
#end
#implementation ViewController
#synthesize tableViewContactData;
#synthesize searchbarContacts;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayTableData = [[NSMutableArray alloc]init];
arraySearchContactData = [[NSMutableArray alloc]init];
[self fetchContactsandAuthorization];
[tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview:tableViewContactData];
}
//Fetching Contact and Authorization access
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
for (CNContact *contact in cnContacts)
{
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers)
{
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[arrayTableData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
[arraySearchContactData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
NSLog(#"The contactsArray are - %#",arrayTableData);
}
dispatch_async(dispatch_get_main_queue(), ^{
[tableViewContactData reloadData];
});
}
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayTableData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.textLabel.text = arrayTableData[indexPath.row];
return cell;
}
#pragma mark - SearchBar Delegate Methods
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
#try
{
[arrayTableData removeAllObjects];
stringSearch = #"YES";
NSString *name = #"";
if ([searchText length] > 0)
{
for (int i = 0; i < [arraySearchContactData count] ; i++)
{
name = [arraySearchContactData objectAtIndex:i];
if (name.length >= searchText.length)
{
NSRange titleResultsRange = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[arrayTableData addObject:[arraySearchContactData objectAtIndex:i]];
}
}
}
}
else
{
[arrayTableData addObjectsFromArray:arraySearchContactData];
}
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)SearchBar
{
SearchBar.showsCancelButton=YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)theSearchBar
{
[theSearchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)SearchBar
{
#try
{
SearchBar.showsCancelButton=NO;
[SearchBar resignFirstResponder];
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)SearchBar
{
[SearchBar resignFirstResponder];
}
#end
The Printed results For Contacts
The contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
)
Please Refer the below link, i can able to implement the search bar in table view by using this.
http://www.appcoda.com/search-bar-tutorial-ios7/
I have been trying to implement a UISearchBar to filter(search) my UITableView since yesterday but no luck.
I added my UISearchBar to my header file like this:
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController<UISearchBarDelegate>{
}
#property (weak, nonatomic) IBOutlet UITableView *TableView;
#property (weak, nonatomic) IBOutlet UISearchBar *mySearchBar;
#property (nonatomic, strong) NSMutableArray *filteredsarkilar;
#property BOOL isFiltered;
#end
I made my UITableView's datasource a NSDictionary with indexes and sections which include titles and subtitles. It works exactly the way I want. Here is the implementation file which I have already tried to implement the search function. And by the way when I press search button the keyboard does not dismiss, why?
#import "TableViewController.h"
#import "DetailViewController.h"
#interface TableViewController (){
NSDictionary *sarkilar;
NSArray *sarkilarSectionTitles;
NSArray *sarkilarIndexTitles;
}
#end
#implementation TableViewController
#synthesize mySearchBar, filteredsarkilar, isFiltered;
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:newButton];
sarkilar = #{
#"A" : #[#{#"title":#"Alayına İsyan",#"subtitle":#"Seslendiren: Mustafa Sandal"},
#{#"title":#"Ardindan",#"subtitle":#"Seslendiren: Sinasi Gurel"}],
#"B" : #[#{#"title":#"Birak Gitsin",#"subtitle":#"Seslendiren: Tarkan"},
#{#"title":#"Buralar",#"subtitle":#"Seslendiren: Duman"}],
#"C" : #[#{#"title":#"Cephaneler",#"subtitle":#"Seslendiren: Burak Kut"},
#{#"title":#"Cari Acik",#"subtitle":#"Seslendiren: Kristal"}],
};
sarkilarSectionTitles = [[sarkilar allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
sarkilarIndexTitles = #[#"A", #"B", #"C",#"Ç", #"D", #"E", #"F", #"G", #"H", #"I",#"İ", #"J", #"K", #"L", #"M", #"N", #"O", #"Ö", #"P", #"R", #"S",#"Ş", #"T", #"U",#"Ü", #"V", #"Y", #"Z"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [sarkilarSectionTitles count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isFiltered == YES) {
return filteredsarkilar.count;
}
else
{
NSString *sectionTitle = [sarkilarSectionTitles objectAtIndex:section];
NSArray *sectionSarkilar = [sarkilar objectForKey:sectionTitle];
return [sectionSarkilar count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [sarkilarSectionTitles objectAtIndex:section];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *sectionTitle = [sarkilarSectionTitles objectAtIndex:indexPath.section];
NSArray *sectionSarkilar = [sarkilar objectForKey:sectionTitle];
NSDictionary *dict = [sectionSarkilar objectAtIndex:indexPath.row];
NSString *title = [dict objectForKey:#"title"];
NSString *subtitle = [dict objectForKey:#"subtitle"];
if (isFiltered == YES) {
cell.textLabel.text = title;
cell.detailTextLabel.text = subtitle;
}
else
{
cell.textLabel.text = title;
cell.detailTextLabel.text = subtitle;
}
CGSize itemSize = CGSizeMake(50, 50);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cell;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return sarkilarIndexTitles;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [sarkilarSectionTitles indexOfObject:title];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered =YES;
filteredsarkilar = [[NSMutableArray alloc]init];
for (NSString *title in sarkilar)
{
NSRange titleRange = [title rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleRange.location != NSNotFound)
{
[filteredsarkilar addObject:title];
}
}
}
[TableView reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[mySearchBar resignFirstResponder];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"ShowDetails"]) {
DetailViewController *destinationViewController = segue.destinationViewController;
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
destinationViewController.title = selectedCell.textLabel.text;
}
}
#end
Please help me if you can, because I've been pulling my hair off my head!! Thank you
I am currently trying to load a plist file from a URL. I'm not sure if the way I have my code set up is causing it to crash or if I'm doing something wrong.
.m file
#import "deptTableViewController.h"
#interface deptTableViewController ()
#property (nonatomic, copy) NSDictionary *names;
#property (nonatomic, copy) NSArray *keys;
#property (nonatomic, strong) NSMutableArray *filterednames;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#end
#implementation deptTableViewController
#synthesize names, keys, filterednames, searchController, searchNames;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UITableView *tableview = (id) [self.view viewWithTag:1];
[tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
filterednames = [[NSMutableArray alloc]init];
searchController = [[UISearchDisplayController alloc]init];
searchController.searchResultsDataSource = self;
// This will get the plist into data format
NSData *dataReturn = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://morphinggamers.ca/staff.plist"]];
NSString *path = [[NSBundle mainBundle]pathForResource:#"staff" ofType:#"plist"];
names = [NSDictionary dictionaryWithContentsOfFile:path];
keys = [[names allKeys]sortedArrayUsingSelector:#selector(compare:)];
keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView.tag == 1) {
return [keys count];
}
else{
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView.tag == 1) {
NSString *key = keys[section];
NSArray *keyValues = names[key];
return [keyValues count];
}
else {
return [filterednames count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (tableView.tag == 1) {
names = keys[indexPath.row];
NSString *teacherNames = names[#"teacherNames"];
cell.textLabel.text = teacherNames;
}
else{
cell.textLabel.text = filterednames [indexPath.row];
}
return cell;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if (tableView.tag == 1) {
return keys[section];
}
else{
return nil;
}
}
#pragma mark - Search Display And Delegate Methods
-(void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[filterednames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searchNames.text];
for (NSString *key in keys) {
NSArray *matches = [names[key]filteredArrayUsingPredicate:predicate];
[filterednames addObjectsFromArray:matches];
}
}
return YES;
}
#end
You can only use initwithcontentsofurl using local files (files on your device already) This URL is on a server so you need to use a network request to fetch the data from the server.
NSURLRequest *request = [NSURLRequest requestWithURL:#"http://morphinggamers.ca/staff.plist"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *names = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:0 format:0 errorDescription:nil];
keys = [[names allKeys]sortedArrayUsingSelector:#selector(compare:)];
keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn];
//might want to reload the tableview
[self.tableview reloadData]
}];
I want to be able to set a label's text to be what is selected from the table view.
#interface STAdvancedBACViewController ()
#property (nonatomic, copy) NSDictionary *brand;
#property (nonatomic, copy) NSArray *keys;
#property (nonatomic, copy) NSMutableArray *filteredNames;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#property (nonatomic, copy) NSDictionary *beerValues;
#property (nonatomic, copy) NSArray *beerKeys;
#end
#implementation STAdvancedBACViewController {
}
#synthesize brand, keys, filteredNames, searchController, beerValues, beerKeys;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UITableView *tableView = (id)[self.view viewWithTag:1];
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"A" ofType:#"plist"];
brand = [NSDictionary dictionaryWithContentsOfFile:path];
keys = [[brand allKeys]sortedArrayUsingSelector:#selector(compare:)];
filteredNames = [[NSMutableArray alloc]init];
searchController = [[UISearchDisplayController alloc]init];
searchController.searchResultsDataSource = self;
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"BEER2" ofType:#"plist"];
beerValues = [NSDictionary dictionaryWithContentsOfFile:path2];
beerKeys = [[beerValues allKeys] sortedArrayUsingSelector:#selector(compare:)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView.tag == 1) {
return [keys count];
}
else{
return 1;
}
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (tableView.tag == 1) {
NSString *key = keys[indexPath.section];
NSArray *keyValues = brand[key];
cell.textLabel.text = keyValues[indexPath.row];
}
else{
cell.textLabel.text = filteredNames[indexPath.row];
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView.tag == 1) {
NSString *key = keys[section];
NSArray *keyValues = brand[key];
return [keyValues count];
}
else {
return [filteredNames count];
}
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if (tableView.tag ==1) {
return keys;
}
else {
return nil;
}
}
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (tableView.tag ==1) {
return keys[section];
}
else {
return nil;
}
}
#pragma mark
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[filteredNames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searchBar.text];
for (NSString *key in keys) {
NSArray *matches = [brand[key]filteredArrayUsingPredicate:predicate];
[filteredNames addObjectsFromArray:matches];
}
}
return YES;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
_testLabel.text = keys[indexPath.row];
}
#end
For some reason this does not return the value in the cell but returns a letter from the Plist file. The plist file was organized such that there were 26 objects that were arrays for each letter of the alphabet and then those were arrays containing the beer names. Basically I want to retrieve the beer name selected by the user.
Though your question is a bit unclear, but I guess you want a label to be the name of the brand that the user selected. In your cellForRowAtIndexPath you are doing this:
if (tableView.tag == 1) {
NSString *key = keys[indexPath.section];
NSArray *keyValues = brand[key];
cell.textLabel.text = keyValues[indexPath.row];
}
else{
cell.textLabel.text = filteredNames[indexPath.row];
}
But in your didDeselectRowAtIndexPath you are just doing this:
_testLabel.text = keys[indexPath.row];
Shouldn't you be doing this in didDeselectRowAtIndexPath:
//Plan your logic accordingly. Its just a rough
if (tableView.tag == 1) {
NSString *key = keys[indexPath.section];
NSArray *keyValues = brand[key];
_testLabel.text = keyValues[indexPath.row];
}
else{
_testLabel.text = filteredNames[indexPath.row];
}
Hope this helps.. :)