Tableview with Search Bar? - ios

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

Related

Use Search Bar using dynamically generated array

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];
}

TableViewCell title and subtitle to detail view controller (segue help)

i got a problem with my tableview segue and the detail view controller. i managed to populate my table view with titles and subtitles with nsdictionary. however i could not push my title and subtitle to the detail view. i need my title to go on the navigation bar and the subtitle to a label in the detail view. here is the code and the screenshots of my table view and the detail view:
#import "TableViewController.h"
#import "DetailViewController.h"
#interface TableViewController (){
NSDictionary *sarkilar;
NSArray *sarkilarSectionTitles;
NSArray *sarkilarIndexTitles;
}
#end
#implementation TableViewController
- (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 {
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"];
cell.textLabel.text = title;
cell.detailTextLabel.text = subtitle;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
// return animalSectionTitles;
return sarkilarIndexTitles;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [sarkilarSectionTitles indexOfObject:title];
}
//-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//
// if ([[segue identifier] isEqualToString:#"ShowDetails"]) {
// DetailViewController *detailView = [segue destinationViewController];
//
// NSIndexPath *myindexpath = [self.tableView indexPathForSelectedRow];
//
// int row = [myindexpath row];
// detailView.DetailModal = #[_title[row], subtitle[row],];
// }
//
//
//
//}
//
#end
as you can see i couldn't figure out how to set my segue up. and here are the screenshots. i hope it is not too much to ask how to set up the segue
You can get the currently selected cell and pass the values in the prepareForSegue: method.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UIViewController *destinationViewController = segue.destinationViewController;
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
destinationViewController.title = selectedCell.textLabel.text;
//Add code to set label to selectedCell.detailTextLabel.text
}
To be clear, you will need to implement the delegate method for when a cell is selected, then call your segue. (Assuming this is the way your app will operate)
//TableViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"ShowDetails" sender:self];
}
Then before the transition the method prepareForSegue will be called, where you can set up any properties on your DetailViewController.
//TableViewController.m
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"ShowDetails"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *detailVC = segue.destinationViewController;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
detailVC.myTitle = cell.textLabel.text;
detailVC.mySubtitle = cell.detailTextLabel.text;
}
}
Add these properties to your DetailViewController header file to pass the references to your title and subtitle.
//DetailViewController.h
#property (nonatomic, strong) NSString *myTitle;
#property (nonatomic, strong) NSString *mySubtitle;
Then in the viewDidLoad method of your DetailViewController set the navigation title and label properties
//DetailViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = self.myTitle;
self.myLabelName.text = self.mySubtitle;
}

Segmented control and Tableview control

I have three differente kind of tableview,
how can I used segmented control to switch to difference tableview?
Here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
tableData1 = [[NSMutableArray alloc] initWithObjects:#"a", #"b", #"c", #"d", #"e", #"f",#"a", #"b", #"c", #"d", #"e", #"f", nil];
tableData2 = [[NSMutableArray alloc] initWithObjects: #"c", #"d", #"e", #"f",#"a", #"b", #"c", #"d", #"e", #"f",#"a", #"b", nil];
thumbnails1 = [[NSMutableArray alloc] initWithObjects:#"a.png", #"b.png", #"c.png", #"d.png", #"e.png", #"f.png",#"a.png", #"b.png", #"c.png", #"d.png", #"e.png", #"f.png", nil];
thumbnails2 = [[NSMutableArray alloc] initWithObjects:#"d.png", #"e.png", #"f.png",#"a.png", #"b.png", #"c.png",#"a.png", #"b.png", #"c.png", #"d.png", #"e.png", #"f.png", nil];
}
and in tableview delegate:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.seg.selectedSegmentIndex==0) {
return [tableData1 count];
}
else if(self.seg.selectedSegmentIndex==1)
{
return [tableData2 count];
}
}
return [tableData1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableViewCell";
TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (self.seg.selectedSegmentIndex==0)
{
cell.nameLabel.text=[tableData1 objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [thumbnails1 objectAtIndex:indexPath.row];
}
else if(self.seg.selectedSegmentIndex==1)
{
cell.nameLabel.text=[tableData2 objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [thumbnails2 objectAtIndex:indexPath.row];
}
return cell;
}
in DidSelectRow part:
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *detail = [[DetailViewController alloc] init];
if (self.seg.selectedSegmentIndex==0)
{
[detail setTitle:[tableData1 objectAtIndex:indexPath.row]];
detail.DetailLabel.text = [tableData1 objectAtIndex:indexPath.row];
detail.DetailImage.image = [thumbnails1 objectAtIndex:indexPath.row];
}
else if(self.seg.selectedSegmentIndex==1)
{
[detail setTitle:[tableData2 objectAtIndex:indexPath.row]];
detail.DetailLabel.text = [tableData2 objectAtIndex:indexPath.row];
detail.DetailImage.image = [thumbnails2 objectAtIndex:indexPath.row];
}
[self.navigationController pushViewController:detail animated:YES];
}
i edited the code...you made many little mistakes...this is the code that you excatly needed...
homePage.h
#import <UIKit/UIKit.h>
#interface homePage : UIViewController
#property (strong, nonatomic) IBOutlet UISegmentedControl *seg;
#property (strong, nonatomic) IBOutlet UITableView *table;
#property (nonatomic,retain)NSMutableArray*tabledata1;
#property (nonatomic,retain)NSMutableArray*tabledata2;
#property (nonatomic,retain)NSMutableArray*thumbnails1;
#property (nonatomic,retain)NSMutableArray*thumbnails2;
- (IBAction)segment:(id)sender;
#end
homepage.m
#implementation homePage
#synthesize tabledata1,tabledata2,thumbnails1,thumbnails2;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
tabledata1=[[NSMutableArray alloc]initWithObjects:#"a", #"b", #"c", #"d", #"e", #"f",#"a", #"b", #"c", #"d", #"e", #"f", nil];
tabledata2=[[NSMutableArray alloc]initWithObjects:#"c", #"d", #"e", #"f",#"a", #"b", #"c", #"d", #"e", #"f",#"a", #"b", nil];
thumbnails1=[[NSMutableArray alloc]initWithObjects:#"a.jpg", #"b.jpg", #"c.jpg", #"d.jpg", #"e.jpg", #"f.jpg",#"a.jpg", #"b.jpg", #"c.jpg", #"d.jpg", #"e.jpg", #"f.jpg", nil];
thumbnails2=[[NSMutableArray alloc]initWithObjects:#"d.jpg", #"e.jpg", #"f.jpg",#"a.jpg", #"b.jpg", #"c.jpg",#"a.jpg", #"b.jpg", #"c.jpg", #"d.jpg", #"e.jpg", #"f.jpg", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.seg.selectedSegmentIndex==0)
{
return [tabledata1 count];
}
else
{
return [tabledata2 count];
}
return [tabledata1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (self.seg.selectedSegmentIndex==0) {
cell.thumbnailImageView.image=[UIImage imageNamed:[thumbnails1 objectAtIndex:indexPath.row]];
cell.nameLabel.text=[tabledata1 objectAtIndex:indexPath.row];
}
else if(self.seg.selectedSegmentIndex==1)
{
cell.thumbnailImageView.image=[UIImage imageNamed:[thumbnails2 objectAtIndex:indexPath.row]];
cell.nameLabel.text=[tabledata2 objectAtIndex:indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
detailPage*detail=[[detailPage alloc]init];
if (self.seg.selectedSegmentIndex==0)
{
detail.DetailLabel_string=[tabledata1 objectAtIndex:indexPath.row];
detail.DetailImage_string=[thumbnails1 objectAtIndex:indexPath.row];
}
else if(self.seg.selectedSegmentIndex==1)
{
detail.DetailLabel_string=[tabledata2 objectAtIndex:indexPath.row];
detail.DetailImage_string=[thumbnails2 objectAtIndex:indexPath.row];
}
[self.navigationController pushViewController:detail animated:YES];
}
- (IBAction)segment:(id)sender
{
[self.table reloadData];
}
detailPage.h
#import <UIKit/UIKit.h>
#interface detailPage : UIViewController
#property(nonatomic,retain)NSString*DetailLabel_string;
#property(nonatomic,retain)NSString*DetailImage_string;
// and also synthesis this two string its necessary.
#property (strong, nonatomic) IBOutlet UILabel *tittlelbl;
#property (strong, nonatomic) IBOutlet UIImageView *imageview;
#end
detailpage.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSLog(#"%#",DetailImage_string);
NSLog(#"%#",DetailLabel_string);
self.tittlelbl.text=DetailLabel_string;
self.imageview.image=[UIImage imageNamed:DetailImage_string];
}
its totally work for me....i did same thing that u may be want....n also care for custom cell......

How can I add default entries into my dictionary so that it is not empty on first run

I need some help trying to insert a couple of default entries in bandsDictionary so that it is not empty before user adds new entries.
// TableViewController.h
#import <UIKit/UIKit.h>
#class WBABand, WBABandDetailsViewController;
#interface WBABandsListTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableDictionary *bandsDictionary;
#property (nonatomic, strong) NSMutableArray *firstLettersArray;
#property (nonatomic, strong) WBABandDetailsViewController *bandInfoViewController;
//NSMutableDictionary *tempDictionary;
#property (nonatomic, retain) NSMutableDictionary *tempDictionary;
-(void)addNewBand:(WBABand*)bandObject;
-(void)saveBandsDictionary;
-(void)loadBandsDictionary;
-(void)deleteBandAtIndexPath:(NSIndexPath*)indexPath;
-(void)updateBandObject:(WBABand*)bandObject atIndexPath:(NSIndexPath*)indexPath;
-(IBAction)addBandTouched:(id)sender;
#end
//TableViewController.m
#import "WBABandsListTableViewController.h"
#import "WBABand.h"
#import "WBABandDetailsViewController.h"
static NSString *bandsDictionarytKey = #"BABandsDictionarytKey";
#interface WBABandsListTableViewController ()
#end
#implementation WBABandsListTableViewController
-(id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
[self loadBandsDictionary];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.clearsSelectionOnViewWillAppear = NO;
}
-(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 self.bandsDictionary.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSString *firstLetter = [self.firstLettersArray objectAtIndex:section];
NSMutableArray *bandsForLetter = [self.bandsDictionary objectForKey:firstLetter];
return bandsForLetter.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *firstLetter = [self.firstLettersArray objectAtIndex:indexPath.section];
NSMutableArray *bandsForLetter = [self.bandsDictionary objectForKey:firstLetter];
WBABand *bandObject = [bandsForLetter objectAtIndex:indexPath.row];
// Configure the cell...
cell.textLabel.text = bandObject.name;
return cell;
}
- (void)addNewBand:(WBABand*)bandObject
{
NSString *bandNameFirstLetter = [bandObject.name substringToIndex:1];
NSMutableArray *bandsForLetter = [self.bandsDictionary objectForKey:bandNameFirstLetter];
if(!bandsForLetter)
bandsForLetter = [NSMutableArray array];
[bandsForLetter addObject:bandObject];
[bandsForLetter sortUsingSelector:#selector(compare:)];
[self.bandsDictionary setObject:bandsForLetter forKey:bandNameFirstLetter];
if(![self.firstLettersArray containsObject:bandNameFirstLetter])
{
[self.firstLettersArray addObject:bandNameFirstLetter];
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
}
[self saveBandsDictionary];
}
- (void)saveBandsDictionary
{
NSData *bandsDictionaryData = [NSKeyedArchiver archivedDataWithRootObject:self.bandsDictionary];
[[NSUserDefaults standardUserDefaults] setObject:bandsDictionaryData forKey:bandsDictionarytKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)loadBandsDictionary
{
NSData *bandsDictionaryData = [[NSUserDefaults standardUserDefaults] objectForKey:bandsDictionarytKey];
if(bandsDictionaryData)
{
self.bandsDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:bandsDictionaryData];
self.firstLettersArray = [NSMutableArray arrayWithArray:self.bandsDictionary.allKeys];
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
}
else
{
self.bandsDictionary = [NSMutableDictionary dictionary];
self.firstLettersArray = [NSMutableArray array];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(self.bandInfoViewController)
{
NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
if(self.bandInfoViewController.saveBand)
{
if(selectedIndexPath)
{
[self updateBandObject:self.bandInfoViewController.bandObject atIndexPath:selectedIndexPath];
[self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
}
else
[self addNewBand:self.bandInfoViewController.bandObject];
[self.tableView reloadData];
}
else if (selectedIndexPath)
{
[self deleteBandAtIndexPath:selectedIndexPath];
}
self.bandInfoViewController = nil;
}
}
- (IBAction)addBandTouched:(id)sender
{
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
self.bandInfoViewController = (WBABandDetailsViewController *)[sb instantiateViewControllerWithIdentifier:#"bandDetails"];
[self presentViewController:self.bandInfoViewController animated:YES completion:nil];
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.firstLettersArray objectAtIndex:section];
}
- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return self.firstLettersArray;
}
- (int)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [self.firstLettersArray indexOfObject:title];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[self deleteBandAtIndexPath:indexPath];
}
}
- (void)deleteBandAtIndexPath:(NSIndexPath*)indexPath
{
NSString *sectionHeader = [self.firstLettersArray objectAtIndex:indexPath.section];
NSMutableArray *bandsForLetter = [self.bandsDictionary objectForKey:sectionHeader];
[bandsForLetter removeObjectAtIndex:indexPath.row];
if(bandsForLetter.count == 0)
{
[self.firstLettersArray removeObject:sectionHeader];
[self.bandsDictionary removeObjectForKey:sectionHeader];
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
}
else
{
[self.bandsDictionary setObject:bandsForLetter forKey:sectionHeader];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
[self saveBandsDictionary];
}
- (void)updateBandObject:(WBABand*)bandObject atIndexPath:(NSIndexPath*)indexPath
{
NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
NSString *sectionHeader = [self.firstLettersArray objectAtIndex:selectedIndexPath.section];
NSMutableArray *bandsForSection = [self.bandsDictionary objectForKey:sectionHeader];
[bandsForSection removeObjectAtIndex:indexPath.row];
[bandsForSection addObject:bandObject];
[bandsForSection sortUsingSelector:#selector(compare:)];
[self.bandsDictionary setObject:bandsForSection forKey:sectionHeader];
[self saveBandsDictionary];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
NSString *sectionHeader = [self.firstLettersArray objectAtIndex:selectedIndexPath.section];
NSMutableArray *bandsForSection = [self.bandsDictionary objectForKey:sectionHeader];
WBABand *bandObject = [bandsForSection objectAtIndex:selectedIndexPath.row];
self.bandInfoViewController = segue.destinationViewController;
self.bandInfoViewController.bandObject = bandObject;
self.bandInfoViewController.saveBand = YES;
}
#end
You can just add some band objects in the else clause of loadBandsDictionary and then save your user defaults. You haven't provided your WBABand class, so I don't know all of the properties, but it would be something like this -
- (void)loadBandsDictionary
{
NSData *bandsDictionaryData = [[NSUserDefaults standardUserDefaults] objectForKey:bandsDictionarytKey];
if(bandsDictionaryData)
{
self.bandsDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:bandsDictionaryData];
self.firstLettersArray = [NSMutableArray arrayWithArray:self.bandsDictionary.allKeys];
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
}
else
{
self.bandsDictionary = [NSMutableDictionary dictionary];
self.firstLettersArray = [NSMutableArray array];
WBABand *sampleBand=[[WBABand alloc]init];
sampleBand.name=#"The Smashing Beatles";
//Set other band properties;
[self addNewBand:sampleBand];
WBABand *secondSampleBand=[[WBABand alloc]init]
secondSampleBand.name=#"Nine Inch Screws";
[self addNewBand:secondSampleBand];
}
}

How do I retrieve information from cell in table view?

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.. :)

Resources