How to pass data back from detail view controller to uitableview? - iphone

In my app i making use of uitable to select category from my list.
my task is,when ever user click or select a cell he should be able to view the selected cell detail in next view(detail view). and when he select the item in a detail view he should be able to move back in a table view and should be able to see the selected item in a rootivew controller.
i am able to navigate properly from tableview to detail view,but i am not able to show the item which is selected in detail view to rootviewcontroller.
please help me out with this issue.
image one is my rootview controller page.
for example : if user select #"make" he will able to see all the releated category of #"make"
. in a next page(which image2).
image to is my detail page.
and when user select #"abarth" it should be display in a rootview controller page(which is page one).
following is my code of rootview controller page:
- (void)viewDidLoad
{
self.car = [[NSArray alloc]initWithObjects:#"Make",#"Model",#"Price Min",#"Price Max",#"State",nil];
[super viewDidLoad];
}
-(NSInteger) numberOfSectionInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.car count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TextCellIdentifier = #"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:TextCellIdentifier];
if (cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextCellIdentifier];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [self.car objectAtIndex:[indexPath row]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (0 == indexPath.row)
{
NSLog(#"0");
self.detailcontroller.title = #"Make";
}
else if (1 == indexPath.row)
{
NSLog(#"1");
self.detailcontroller.title = #"Model";
}
else if (2 == indexPath.row)
{
NSLog(#"2");
self.detailcontroller.title = #"Price Min";
}
else if (3 == indexPath.row)
{
self.detailcontroller.title = #"Price Max";
}
else if (4 == indexPath.row)
{
NSLog(#"3");
self.detailcontroller.title = #"State";
}
[self.navigationController
pushViewController:self.detailcontroller
animated:YES];
}
following is my detail view page code:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([self.title isEqualToString:#"Make"])
{
detail = [[NSArray alloc]initWithObjects:#"Any Make",#"Abarth",#"AC",#"ADAYER",#"Adelaide",#"ALFA ROMEO",#"ALLARD",#"ALPINE-RENAULT",#"ALVIS",#"ARMSTRONG",
#"ASTON MARTIN",#"AUDI",#"AUSTIN",#"AUSTIN HEALEY",#"Barossa",#"BEDFORD",
#"BENTLEY",#"BERTONE",#"BMW",#"BOLWELL",#"BRISTOL",#"BUICK",#"BULLET",
#"CADILLAC",#"CATERHAM",#"CHERY",#"CHEVROLET",#"CHRYSLER",#"CITROEN",
#"Country Central",#"CSV",#"CUSTOM",#"DAEWOO",#"DAIHATSU",#"DAIMLER",
#"DATSUN",#"DE TOMASO",#"DELOREAN",#"DODGE",#"ELFIN",#"ESSEX",
#"EUNOS",#"EXCALIBUR",#"FERRARI",nil];
if ([self.title isEqualToString:#"Abarth"])
{
detail = [[NSArray alloc]initWithObjects:#"HI", nil];
}
}
else if ([self.title isEqualToString:#"Model"])
{
detail = [[NSArray alloc]initWithObjects:#"Any Model", nil];
}
else if ([self.title isEqualToString:#"Price Min"])
{
detail = [[NSArray alloc]initWithObjects:#"Min",#"$2,500",
#"$5,000",
#"$7,500",
#"$10,000",
#"$15,000",
#"$20,000",
#"$25,000",
#"$30,000",
#"$35,000",
#"$40,000",
#"$45,000",
#"$50,000",
#"$60,000",
#"$70,000",
#"$80,000",
#"$90,000",
#"$100,000",
#"$500,000",
#"$1,000,000",nil];
}
else if ([self.title isEqualToString:#"Price Max"])
{
detail = [[NSArray alloc]initWithObjects:#"Max",
#"$2,500",
#"$5,000",
#"$7,500",
#"$10,000",
#"$15,000",
#"$20,000",
#"$25,000",
#"$30,000",
#"$35,000",
#"$40,000",
#"$45,000",
#"$50,000",
#"$60,000",
#"$70,000",
#"$80,000",
#"$90,000",
#"$100,000",
#"$500,000",
#"$1,000,000",nil];
}
else if ([self.title isEqualToString:#"State"])
{
detail = [[NSArray alloc]initWithObjects:#"Any State",
#"Australian Capital Territory",
#"New South Wales",
#"Northern Territory",
#"Queensland",
#"South Australia",
#"Tasmania",
#"Victoria",
#"Western Australia",nil];
}
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [detail 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];
}
cell.textLabel.text = [detail objectAtIndex:
[indexPath row]];
cell.font = [UIFont systemFontOfSize:14.0];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.navigationController popViewControllerAnimated:YES];
}

You need to make use of custom delegates. Create a protocol in your detailview and implement it in your rootview.Pass the selected string as parameter to delegate method and from the delegate method, display it in your textfield.
//something like this
#interface detailViewController
// protocol declaration
#protocol myDelegate
#optional
-(void)selectedValueIs:(NSString *)value;
// set it as the property
#property (nonatomic, assign) id<myDelegate> selectedValueDelegate;
// in your implementation class synthesize it and call the delegate method
#implementation detailViewController
#synthesize selectedValueDelegate
// in your didselectRowAtIndex method call this delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self selectedValueDelegate])selectedValueIs:valueString] ;
[self.navigationController popViewControllerAnimated:YES];
}
#end
// In your rootViewController conform to this protocol and then set the delegate
detailViewCtrlObj.selectedValueDelegate=self;
//Implement the delegate Method
-(void)selectedValueIs:(NSString *)value{
{
// do whatever you want with the value string
}

Hi you will have to do it using protocols and delegate
Please see my linkon protocol and delegate
you can also do it by creating a variable in appdelegate , setting its property and accessing it in any other view .
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
delegate.yourVariable;

Related

UITableView indexPathForSelectedRow return 0 (incorrect value)

I'm trying to make an upcoming events table in my app but when I select a row indexPathForSelectedRow always returns 0.
NSArray *upcommingTitle;
NSMutableArray *upcommingSubtitle;
NSMutableArray *upcommingTime;
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)datesTable numberOfRowsInSection:(NSInteger)section
{
return upcommingTitle.count;
}
-(UITableViewCell *)tableView:(UITableView *)datesTable cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
DatesCustomCell *Cell = [datesTable dequeueReusableCellWithIdentifier:cellIdentifier];
if(!Cell)
{
Cell = [[DatesCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
Cell.DatesTitle.text = [upcommingTitle objectAtIndex:indexPath.row];
Cell.DatesSubtitle.text = [upcommingSubtitle objectAtIndex:indexPath.row];
Cell.DatesTime.text = [upcommingTime objectAtIndex:indexPath.row];
return Cell;
}
self.datesTable.dataSource = self;
self.datesTable.delegate = self;
View Did Load
upcommingTitle = [[NSMutableArray alloc] initWithObjects:#"Title1", #"Title2", nil];
upcommingSubtitle = [[NSMutableArray alloc] initWithObjects:#"Sub1", #"Sub2", nil];
upcommingTime = [[NSMutableArray alloc] initWithObjects:#"Date1", #"Date2", nil];
But the following always returns 0 resulting in the "test" label to be "Title1"
View Did Appear
_test.text = [upcommingTitle objectAtIndex:self.datesTable.indexPathForSelectedRow.row];
Thanks for you help
try to push your another view in your didSelect method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Here, indexpath returns the selection of cell's indexpath, so put your code here
_test.text = [upcommingTitle objectAtIndex:indexPath.row];
//then push your view
}
UPDATED : then use this code
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier]isEqualToString:#"pushView"])
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
PushingViewController *pushView = [segue destinationViewController];
pushView._test.text = [upcommingTitle objectAtIndex:indexPath.row];
}
}
(void)tableView:(UITableView *)datesTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_test.text = [upcommingTitle objectAtIndex:indexPath.row];
}
Just put this code in your application.
Try not to deselect cell before presenting your seque
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//Call This Line
[self performSegueWithIdentifier:#"ShowMobileShopStore" sender:nil];
//Before This
[tableView deselectRowAtIndexPath:indexPath animated:true];
}
The initial question was: indexPathForSelectedRow return 0 (incorrect value),
Well, this is by-design, from the apple developer notes, the value returns an the IndexPath which can be NULL (is what you are seeing).
So, to do things right:
1) You need to test if the indexPathForSelectedRow is NOT NULL first
2) If it's not NULL then it would contain (.row) which would then give you the selected row-index, this starts from 0.
3) Please note that indexPathForSelectedRow.row would return ZERO in the case of indexPathForSelectedRow is NULL.
Here is the code that I've tested and works:
if (MyTableViewList.indexPathForSelectedRow)
{
long SelectedRow = MyTableViewList.indexPathForSelectedRow.row;
}
I hope this helps,

How to make SearchBar in tableview work?

So i am trying to make an application that displays names of people in a tableview and on tap moves to the next view controller that shows an image of the person.
However when i add the search bar on the table view; i dont seem to have it right.
What am i doing wrong here?
The code compiles and displays on the simulator but when i click on any of the buttons, it gives me the errors i hate the most (Thread 1 : signal SIGABRT)
Here is my code for the Table View Controller
#import "PhotoTableViewController.h"
#import "Photo.h"
#import "DisplayViewController.h"
#interface PhotoTableViewController ()
#end
#implementation PhotoTableViewController
#synthesize photoSearchBar, showPhotos, filteredPhotos;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
showPhotos = [NSArray arrayWithObjects:
[Photo photoofname:#"Main" filename:#"photo1.jpg" notes:#"Amazing Road Bike"],
[Photo photoofname:#"Back" filename:#"photo3.jpg" notes:#"this is the back"], nil];
[self.tableView reloadData];
self.filteredPhotos = [NSMutableArray arrayWithCapacity:[showPhotos count]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredPhotos count];
} else {
return [showPhotos count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Photo *photo = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
photo = [filteredPhotos objectAtIndex:indexPath.row];
}else
{
photo = [showPhotos objectAtIndex:indexPath.row];
}
cell.textLabel.text = photo.name;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.filteredPhotos removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.name contains[c] %#",searchText];
filteredPhotos = [NSMutableArray arrayWithArray:[showPhotos filteredArrayUsingPredicate:predicate]];
}
#pragma mark - UISearchDisplayController Delegate Methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// Tells the table data source to reload when text changes
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
// Tells the table data source to reload when scope bar selection changes
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
#pragma mark - TableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Perform segue to candy detail
[self performSegueWithIdentifier:#"candyDetail" sender:tableView];
}
#pragma mark - Segue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"photoDetail"]) {
UIViewController *candyDetailViewController = [segue destinationViewController];
// In order to manipulate the destination view controller, another check on which table (search or normal) is displayed is needed
if(sender == self.searchDisplayController.searchResultsTableView) {
NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
NSString *destinationTitle = [[filteredPhotos objectAtIndex:[indexPath row]] name];
[candyDetailViewController setTitle:destinationTitle];
}
else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *destinationTitle = [[showPhotos objectAtIndex:[indexPath row]] name];
[candyDetailViewController setTitle:destinationTitle];
}
}
}
Also this is the code for my Objective C Class called Photo
#import "Photo.h"
#implementation Photo
#synthesize name,filename,notes;
+(id) photoofname: (NSString*)name filename:(NSString*)filename notes:(NSString*)notes{
Photo *newPhoto = [[Photo alloc]init];
newPhoto.name = name;
newPhoto.filename = filename;
newPhoto.notes = notes;
return newPhoto;
}
#end
Well, just by looking at the code what I can suggest you is, first remove that call to prepareForSegue method called in UITableView's delegate method, didSelectForRowAtIndexPath.
You are overriding prepareForSegue, so in your storyboard you should have a prototype cell from where you have to ctrl-drag to the destination controller and segue it accordingly. That's a basic concept. Still having problem? Let us see your console messages when it crashes.

uitableview reloadRowsAtIndexPaths not working

I have a tableviewcell in the RegisterViewController, when i click on it, it push to the SelectCityViewController where i can pick a city from a uipickerview. and I have defined a delegate in the SelectCityViewController. But when i implement the delegate method, i got the city back from the pickerview and the selected indexpath from didSelectRowAtIndexPath in RegisterViewController. When i check the log, i get the city, and the selected indexpath. but when i call reloadRowsAtIndexPaths, the cell still got the old titlelabel text. the code:
SelectCityViewController.h
#protocol SelectCityDelegate <NSObject>
- (void)didGetCity:(City *)city;
#end
SelectCityViewController.m
- (void)finished:(UIBarButtonItem *)buttonItem
{
if ([self.delegate respondsToSelector:#selector(didGetCity:)]) {
[self.delegate didGetCity:self.city];
}
NSLog(#"%#", self.city.city);
[self.navigationController popViewControllerAnimated:YES];
}
RegisterViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 2) {
self.selectedIndexPath = indexPath;
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:#"MainStoryboard_iPhone" bundle:nil];
SelectCityViewController *signUp = [storyBoard instantiateViewControllerWithIdentifier:#"SignVC"];
signUp.delegate = self;
[self.navigationController pushViewController:signUp animated:YES];
}
}
- (void)didGetCity:(City *)city
{
NSLog(#"%#", city.city);
NSLog(#"%#", selectedIndexPath);
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIndexPath];
cell.textLabel.text = city.city;
[self.tableView reloadRowsAtIndexPaths:#[selectedIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}
I think the problem is in the below code you don't have to set the value here, because when you will reload, it will override the value with what is in the function where you are creating your cells.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIndexPath];
cell.textLabel.text = city.city;
Just reload the cell, and put above code in your
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Cell intialization and other things
cell.textLabel.text = city.city;
}
didGetCity needs to update the model that backs the table, not the table cell itself. How do you answer numberOfRowsInSection:? With the count of some array?
That array at index selectedIndexPath.row needs to change. cellForRowAtIndexPath: should initialize the cell with that same data. Then your didGetCity method updates the array and reloads. It should not refer to cells.

Accessing UITextField in UITableViewCell

I'm using a UITableView with a subclassed prototype cell with a UITextField. The cell is used 4 times total in 4 sections. This is the code for it:
...
- (void)viewDidLoad
{
[super viewDidLoad];
cellTitles = [[NSArray alloc] initWithObjects:#"Smell", #"Taste", #"Suits", #"Notes", nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [cellTitles count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cellTitles count] / [cellTitles count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [cellTitles objectAtIndex:section];
}
- (AddInfoCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"AddInfoCell";
AddInfoCell *addInfoCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (addInfoCell == nil) {
addInfoCell = [[AddInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
addInfoCell.cellTextView.delegate = self;
return addInfoCell;
}
I want to add the text from each cell to the dataSource object:
-(IBAction)nextButtonPressed:(id)sender {
...
[[dataSource objectAtIndex:dataSourceIndex] setObject:* forKey:#"Smellnote"];
[[dataSource objectAtIndex:dataSourceIndex] setObject:** forKey:#"Tastenote"];
//etc
…
}
*text from cell 1
**text from cell 2
How can I access the text that I want?
Maybe you're looking at it wrong. Why not make the delegate for the textField be the cell itself, ie, in the Cell's class, set the delegate to File'sOwner or self in the init... method.
Create a reference to the dataSource and pass the dataSource to your cell, along with the #"Key" for your dictionary.
cell.dataSource = self.dictionary;
cell.dataKey = #"Tastenote";
//in cell .m
//textFieldDelegate method...
[self.dataSource setObject:self.cellTextView.text forKey:self.dataKey];

ios push array to uitableview

The best answer on stackoverflow for pushing an array to a tableView cell is "start with something easier". I think we can do better than that...
I believe I have everything in place except I can not find the proper way to address getting the data from the rootView. See Below.
The below code pushes an array to DetailView Controller with three cells in a group with "Get Cell Info Here" in top cell. Can someone explain what I need to do to get the actual data into the top cell? Thanks
RootViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
DetailViewController *selectedCell = [[DetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
[self.navigationController pushViewController:selectedCell animated:YES];
}
DetailViewController.h
#interface DetailViewController : UITableViewController {
NSArray *displayCell;
}
#end
DetailViewController.m
- (void)viewWillAppear:(BOOL)animated
{
//Display the selected cell data
displayCell = [[NSArray alloc] initWithObjects:#"Get Cell Info Here", nil];
//Set the title of the navigation bar
self.navigationItem.title = #"wtf";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] ;
// Make cell unselectable
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *cellText = nil;
switch ( indexPath.row ) {
case 0: {
cellText = [displayCell objectAtIndex:indexPath.row];
break ;
}
case 1: {
break ;
}
case 2: {
break ;
default:
break;
}
}
cell.textLabel.text = cellText;
return cell;
}
Add a property to DetailViewController as follows:
#property (nonatomic, retain) NSArray *passedItems;
Then have root view controller pass the items as follows:
selectedCell.passedItems = passedItems; // passedItems is array in rootview controller
Then you can use passedItems in DetailedViewController.