I have an app made with the default template master-detail. I want to pass a string from detail view to master view tapping on a button. I used this code:
Detailviewcontroller.h
#protocol DetailViewControllerDelegate <NSObject>
- (void)passItemToMaster:(id)controller didFinishEnteringItem:(NSString *)item;
#end
#interface DetailViewController : UIViewController<UITextFieldDelegate>
{
NSString *itemToPassBack;
}
#property (copy) NSString *itemToPassBack;
#property (retain) id delegate;
#end
Detailviewcontroller.m
-(IBAction)passBack:(id)sender
{
itemToPassBack = [[NSString alloc] initWithFormat:#"PassedBack"];
[[self delegate] addItemViewController:self didFinishEnteringItem: itemToPassBack];
[self.navigationController popViewControllerAnimated:YES];
}
Masterviewcontroller.h
#interface MasterViewController : UITableViewController <DetailViewControllerDelegate>
#property (nonatomic) NSString *returnedItem;
#end
Masterviewcontroller.m
-(void) passItemToMaster:(id) controller didFinishEnteringItem: (NSString *)item
{
returnedItem = item;
NSLog(#"This was returned from secondPageViewController");
}
How to get the object in master view? nslog doesn't show anything.
When you create your DetailView from masterViewController, add this line :
_detailViewController.delegate = self;
Replace your prepereForSeguelike this :
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSString *object = _nameField.text;
DetailViewController *detailViewController = segue.destinationViewController
detailViewController.delegate = self;
[[segue destinationViewController] setDetailItem:object];
}
}
You can get a delegate object/property like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.object;
[appDelegate property];
Thanks for answers. Let's say i'm new to programming in Xcode and i have to understand better delegates. i used the template and i modified just a couple of things.so i had this masterviewcontroller.m
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize returnedItem;
-(void) addItemViewController:(id) controller didFinishEnteringItem: (NSString *)item
{
returnedItem = item;
NSLog(#"This was returned from secondPageViewController");
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
//create new cell
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
CGRect frame = CGRectMake (68, 12, 225, 22);
UITextField *textfield = [[UITextField alloc] initWithFrame:frame];
[self setNameField:textfield];
[_nameField setDelegate:self];
[_nameField setReturnKeyType:UIReturnKeyDone];
[_nameField addTarget:self
action:#selector(textFieldFinished:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[cell.contentView addSubview: _nameField];
cell.textLabel.enabled = YES;
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
- (void)textFieldFinished:(id)sender{
[sender resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *title = [_objects objectAtIndex: [fromIndexPath row]];
[_objects removeObjectAtIndex:[fromIndexPath row]];
[_objects insertObject:title atIndex:[toIndexPath row]];
[[self tableView] reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSString *object = _nameField.text;
[[segue destinationViewController] setDetailItem:object];
}
}
#end
i don't know where to define delegate.
Related
I have a HabitViewController (UITableViewController) with a button to add cells. When a cell is added its default title is "New Habit". Then the user can tap the cell and a detailViewController appears with a picker to choose the habit. The cell.label.text is then set to the selected option in the picker. This is where my problem is. For example, if i added 3 cells by pressing the button three times, then selected the third row. And then I chose the option Hello World. The top cell would be named hello world, not the third cell. Is this normal? Here is my code:
HabitViewController.h
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#interface HabitViewController : UITableViewController <DetailViewDelegate> {
}
#property (nonatomic, strong) NSString *cellNameSender;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) NSIndexPath *selectedCell;
#end
.m
#import "HabitViewController.h"
#import "DetailViewController.h"
#interface HabitViewController () {
NSMutableArray *myCells;
}
#property(strong, nonatomic) NSString *cellName2;
#end
#implementation HabitViewController
#synthesize cellNameSender, selectedCell;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
[self.editButtonItem setTintColor:[UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1]];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
addButton.tintColor = [UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"nav_bar.png"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidAppear:(BOOL)animated {
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)insertNewObject:(id)sender
{
if (!myCells) {
myCells = [[NSMutableArray alloc] init];
}
[myCells insertObject:#"New Habit" atIndex:0];
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[path] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myCells.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = myCells[indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[myCells removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DetailViewController *vc = segue.destinationViewController;
vc.delegate = self;
}
#pragma mark - DetailViewDelegate
-(void)setCellName2:(NSString *)cellName {
NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row;
[myCells replaceObjectAtIndex:selectedRow withObject:cellName];
[self.tableView reloadData];
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#protocol DetailViewDelegate <NSObject>
- (void)setCellName2:(NSString *)cellName;
#end
#interface DetailViewController : UIViewController<UIPickerViewDelegate> {
NSArray *PickerData;
}
#property (weak, nonatomic) IBOutlet UITextField *habitField;
#property (strong, nonatomic) UIToolbar *toolBar;
#property (weak, nonatomic) id<DetailViewDelegate> delegate;
#property (nonatomic, strong) NSString *cellName;
#property (nonatomic, strong) UIBarButtonItem *backButton;
#property (nonatomic, strong) UIPickerView *Picker;
#property (retain, nonatomic) NSArray *PickerData;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *doneButton;
#property (nonatomic, strong) UIBarButtonItem *barDoneButton;
#property (nonatomic, strong) UIBarButtonItem *flexSpace;
#property (nonatomic, strong) NSString *customHabit;
- (IBAction)backToRoot:(id)sender;
#end
.m
#import "DetailViewController.h"
#import "HabitViewController.h"
#interface DetailViewController () {
}
#end
#implementation DetailViewController
#synthesize PickerData, Picker, toolBar, backButton, barDoneButton, flexSpace;
- (void)viewDidLoad
{
[super viewDidLoad];
self.pickerData = #[#"Posture",#"Paludies Abbs",#"Custom"];
[self.delegate setCellName2:self.cellName];
toolBar = [[UIToolbar alloc] init];
toolBar.barStyle = UIBarStyleBlackOpaque;
[toolBar sizeToFit];
[toolBar setBackgroundImage:[UIImage imageNamed:#"red_navigation_bar.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self
action:nil];
// Done button on toolbar
barDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(releasePicker)];
// Back button on toolbar
backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back"style:UIBarButtonItemStyleDone
target:self
action:#selector(backToPicker)];
// Habit PickerView
Picker = [[UIPickerView alloc] init];
Picker.showsSelectionIndicator = YES;
Picker.delegate = self;
barDoneButton.image = [UIImage imageNamed:#"button.png"];
// Toolbar above picker
[toolBar setItems:#[flexSpace, barDoneButton] animated:YES];
self.habitField.inputAccessoryView = toolBar;
[self.habitField addTarget:self action:#selector(customHabitChanged) forControlEvents:UIControlEventEditingChanged];
[self.habitField setInputView:Picker];
}
- (void)customHabitChanged {
self.customHabit = self.habitField.text;
self.cellName = self.customHabit;
NSLog(#"%#", self.customHabit);
[self.delegate setCellName2:self.cellName];
}
- (void)backToPicker {
[toolBar setItems:#[flexSpace, barDoneButton] animated:YES];
[self.habitField resignFirstResponder];
[self.habitField setInputView:Picker];
[self.habitField becomeFirstResponder];
}
- (void)releasePicker {
[self.habitField resignFirstResponder];
[self.habitField setInputView:Picker];
[toolBar setItems:#[flexSpace, barDoneButton] animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)backToRoot:(id)sender {
[self.navigationController popToRootViewControllerAnimated:YES];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [PickerData count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [PickerData objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
[self.delegate setCellName2:self.PickerData[row]];
/* int select = row;
if (select == 0) {
self.cellName = #"Posture";
self.habitField.text = #"Posture";
[self.delegate setCellName2:self.cellName];
NSLog(#"%# Is Selected", self.cellName);
}
if (select == 1) {
self.cellName = #"Palaudies Abbs";
self.habitField.text = #"Palaudies Abbs";
[self.delegate setCellName2:self.cellName];
NSLog(#"%# Is Selected", self.cellName);
}
if (select == 2) {
[self.habitField resignFirstResponder];
[self.habitField setInputView:nil];
[self.habitField becomeFirstResponder];
[toolBar setItems:#[backButton, flexSpace, barDoneButton] animated:YES];
self.habitField.text = #"";
self.habitField.placeholder = #"Custom";
[self.delegate setCellName2:self.cellName];
NSLog(#"%# Is Selected", self.cellName);
*/ //}
}
IN cellForRowAtIndexPath
if(indexPath.row == object.count-1)
cell.textLabel.text = #"New Habit";
else
{
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
}
return cell;
Your thinking on this is not right. You shouldn't think in terms of setting the title of a cell, but instead think about updating the array that you use to populate the table view with data. Here is a simplified version of your app. When you click the add button it adds a new cell in row 0 with the label's text being "New Habit". When you click on that cell (or any other), it takes you to the controller with the picker view where you choose a string, and that string is passed back to the table view in a delegate method. In that method I update the array, myCells with that passed in string at the correct index gotten from the table's indexPathForSelectedRow, and then call reloadData on the table view to update it's view.
This is the table view controller:
#import "TableController.h"
#import "ViewController.h"
#interface TableController ()
#property (strong,nonatomic) NSMutableArray *myCells;
#end
#implementation TableController
- (IBAction)insertNewObject:(UIBarButtonItem *)sender
{
if (!self.myCells) {
self.myCells = [[NSMutableArray alloc] init];
}
[self.myCells insertObject:#"New Habit" atIndex:0];
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[path] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.myCells.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.myCells[indexPath.row];
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
ViewController *vc = segue.destinationViewController;
vc.delegate = self;
}
-(void)setCellName2:(NSString *)cellName {
NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row;
[self.myCells replaceObjectAtIndex:selectedRow withObject:cellName];
[self.tableView reloadData];
}
Here is the controller (ViewController) with the picker view:
#interface ViewController ()
#property (strong,nonatomic) NSArray *pickerData;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.pickerData = #[#"Posture",#"Paludies Abbs",#"Custom"];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [self.pickerData count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [self.pickerData objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
[self.delegate setCellName2:self.pickerData[row]];
}
So far I have made a UITableView in a HabitViewControlle with a button to add a new cell. When the cell is tapped, a detialViewController is revealed. In this View their is a textField, that when tapped a UIPicker is launched. I want to set the title of a tableViewCell to the picker selection.. I have made a string called cellName and I can send it to the other ViewController. I also made it so that when the picker is changed, I set the string cellName to the title I want the cell to be when the picker selection is selected. So I almost have it ready, except actually setting the cell title to the string when the cellName is set, and the picker selection has changed. If this didn't make sense, send a comment to me, and I will try to help, because I hard time writing my question into words
habitViewController.h
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#interface HabitViewController : UITableViewController <DetailViewDelegate> {
UITableViewCell *cell;
}
#end
.m
#import "HabitViewController.h"
#import "DetailViewController.h"
#interface HabitViewController () {
NSMutableArray *_objects;
}
#property(strong, nonatomic) NSString *cellName2;
#end
#implementation HabitViewController
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
[self.editButtonItem setTintColor:[UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1]];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
addButton.tintColor = [UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"nav_bar.png"] forBarMetrics:UIBarMetricsDefault];
//if ([cellName isEqualToString:#"Hello World"]) {
// }
}
- (void)viewDidAppear:(BOOL)animated {
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
cell.textLabel.text = #"New Habit";
NSLog(#"%#",self.cellName2);
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:#"showDetail"]) {
/* assigning self as delegate, telling the detail view that I implement
* setCellName2:, so it (the detailVC) can call it whenever it wants to.
*/
[segue.destinationViewController setDelegate:self];
}
}
#pragma mark - DetailViewDelegate
// note: this is just a property setter so this is not actually needed
- (void)setCellName2:(NSString *)cellName {
cellName = cellName;
NSLog(#"%#",cellName);
cell.textLabel.text = cellName;
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#protocol DetailViewDelegate <NSObject>
- (void)setCellName2:(NSString *)cellName;
#end
#interface DetailViewController : UIViewController<UIPickerViewDelegate> {
NSArray *PickerData;
}
#property (weak, nonatomic) IBOutlet UITextField *habitField;
#property (weak, nonatomic) id<DetailViewDelegate> delegate;
#property (nonatomic, strong) NSString *cellName;
#property (retain, nonatomic) NSArray *PickerData;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *doneButton;
- (IBAction)backToRoot:(id)sender;
#end
.m
#import "DetailViewController.h"
#import "HabitViewController.h"
#interface DetailViewController () {
UITableViewCell *_cell;
}
#end
#implementation DetailViewController
#synthesize PickerData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:#"Posture",#"Paludies Abbs",#"Custom", nil];
self.PickerData = array;
[self.delegate setCellName2:self.cellName];
UIToolbar *toolBar = [[UIToolbar alloc] init];
toolBar.barStyle = UIBarStyleBlackOpaque;
[toolBar sizeToFit];
[toolBar setBackgroundImage:[UIImage imageNamed:#"red_navigation_bar.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self
action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(releasePicker)];
UIPickerView *Picker = [[UIPickerView alloc] init];
Picker.showsSelectionIndicator = YES;
Picker.delegate = self;
doneButton.image = [UIImage imageNamed:#"button.png"];
[toolBar setItems:#[flexSpace, doneButton] animated:YES];
self.habitField.inputAccessoryView = toolBar;
[self.habitField setInputView:Picker];
}
- (void)releasePicker {
[self.habitField resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)backToRoot:(id)sender {
[self.navigationController popToRootViewControllerAnimated:YES];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [PickerData count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [self.PickerData objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
int select = row;
if (select == 0) {
self.cellName = #"Posture";
[self.view reloadInputViews];
NSLog(#"%# Is Selected", self.cellName);
}
}
#end
I think that you want to use your delegate to set your picker in the didSelectRow method. Like this:
DetailViewController.m:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
int select = row;
if (select == 0) {
self.cellName = #"Posture";
[self.delegate setCellName2:self.cellName];
NSLog(#"%# Is Selected", self.cellName);
}
}
and back in your habitViewController:
- (void)setCellName2:(NSString *)cellName {
cellName = cellName;
NSLog(#"%#",cellName);
selectedCell.textLabel.text = cellName;
[self.tableView reloadData];
}
You also have a few problems with "cell". Assuming you have many rows, this will get re-used over and over again and will always contain the last cell it displayed, which will seldom be what you expect.
I would rename it to selectedCell and set it when the cell is touched and your other view triggered.
#interface HabitViewController : UITableViewController <DetailViewDelegate> {
UITableViewCell *savedCell;
}
I would set it here:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:#"showDetail"]) {
if ([sender isKindOfClass[UITableViewCell class]]) {
savedCell = (UITableViewCell *)sender;
}
/* assigning self as delegate, telling the detail view that I implement
* setCellName2:, so it (the detailVC) can call it whenever it wants to.
*/
[segue.destinationViewController setDelegate:self];
}
}
I would just use a temp cell in this method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
cell.textLabel.text = #"New Habit";
NSLog(#"%#",self.cellName2);
return cell;
}
I fixed it with this
First in your habitViewController.h do the following :
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#interface HabitViewController : UITableViewController <DetailViewDelegate> {
UITableViewCell *cell;
}
#property (nonatomic, strong) NSString *cellNameSender;
#end
Then in your .m replace the code that looks like this with the following :
- (void)setCellName2:(NSString *)cellName {
cellName = cellName;
NSLog(#"%#",cellName);
self.cellNameSender = cellName;
}
#end
and the same with this
- (void)viewDidAppear:(BOOL)animated {
cell.textLabel.text = self.cellNameSender;
}
Now the tableViewCell should show the posture is posture is selected.
This is my custom table view cell, I want to change those values in every 1 minute (values will load from server). I have already set an Nstimer and tried to reload the tableview. Data in my array is changing fine, but value in the uitableviewcell is not changing.
Code:
Tableviewcontroller.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
//UITableView *tv = (UITableView *)self.view;
[self.tableview reloadData];
// NSIndexPath *a = [NSIndexPath indexPathForRow:0 inSection:0]; // I wanted to update this cell specifically
// NearestListCell *c = (NearestListCell *)[tv cellForRowAtIndexPath:a];
//c.count=[usercount objectAtIndex:0];
//[tv beginUpdates];
//// [tv reloadRowsAtIndexPaths:usercount withRowAnimation:UITableViewRowAnimationRight];
//[tv endUpdates];
// [tv reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.h
#interface Viewcontroller : UIViewController
{
Tableviewcontroller *Tablecontroller;
IBOutlet UITableView *myTable;
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
}
Please try this code : its working fine here
/* FirstTVContoller.h */
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#end
/* FirstTVContoller.m */
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#implementation FirstTVContoller
-(void) loadView
{
if (items == nil) {
items = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[items objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
[items removeObjectAtIndex:indexPath.row];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void) dealloc
{
[items release];
[super dealloc];
}
#end
/* SecondTVController.h */
#import <Foundation/Foundation.h>
#interface SecondTVController : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
int numberOfCells;
}
#end
/* SecondTVController.m */
#import "SecondTVController.h"
#implementation SecondTVController
-(void) viewDidLoad
{
numberOfCells = 20;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return numberOfCells;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"2.%d", indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
numberOfCells -=1;
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#end
/* TwoTableViewsViewController.h */
#import <UIKit/UIKit.h>
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#interface TwoTableViewsViewController : UIViewController{
FirstTVContoller *firstController;
SecondTVController *secondController;
IBOutlet UITableView *firstTable;
IBOutlet UITableView *secondTable;
}
#end
/* TwoTableViewsViewController.m */
#import "TwoTableViewsViewController.h"
#implementation TwoTableViewsViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)dealloc {
[firstController release];
[secondController release];
[firstTable release];
[secondTable release];
[super dealloc];
}
Let me know if you still face any problems. This will work for sure for n-no. of UITableViews.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UITableViewController
#end
ViewController.m
#import "ViewController1.h"
#implementation ViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
[self.tableView reloadData];
}
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
Please try this code and let me know if you face any problems.Thanks
Why don't you try
[self.tableView reloadData];
instead of
UITableView *tv = (UITableView *)self.view;
[tv reloadData];
Only if your super class is UITableViewController.If not then make an outlet for tableView and reload table through it.
have you used this 'setNeedsDisplay' as
[cell.data11 setNeedsDisplay] if cellForRow is calling.
Please change below code :
/* TwoTableViewsViewController.m */
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadData:) name:#"ReloadFirstTable" object:nil];
}
-(void)reloadData:(id)sender
{
[firstTable reloadData];
}
/* FirstTVContoller.m */
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
self.items = [NSMutableArray arrayWithObjects:#"data1",#" data2 ", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadFirstTable" object:nil];
}
Please use NSNotificationCenter to reload Data.
I fixed the issue. Forgot to reload UITableview object in viewcontroller. I removed the NStimer from Tableviewcontroller.m and placed it in the Viewcontroller.m.
The changed code:
TableViewController.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
**// removed the nstimer from here.**
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Added these 2 lines of code here.
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:[parsejson getNearestUsercount:[defaults valueForKey:#"userid"]],#" 0 ", nil];
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
// I Put the Nstimer here.
aTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 // start timer ( interval 2 secs )
target:self
selector:#selector(timerTicked:)
userInfo:nil
repeats:YES];
}
- (void)timerTicked:(NSTimer*)timer
{
[myTable.self reloadData];
}
Thank You all for helping me.
RootViewController.h
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
NSMutableArray *petsArray;
}
#property (nonatomic, strong) NSMutableArray *petsArray;
#end
RootViewController.m
#import "RootViewController.h"
#import "PetsViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
petsArray = [[NSMutableArray alloc] init];
[petsArray addObject:#"Dog"];
[petsArray addObject:#"Cat"];
[petsArray addObject:#"Snake"];
[self setTitle:#"PETS !"];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [petsArray 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];
}
// Configure the cell...
cell.textLabel.text = [petsArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
I think that the problem is in didSelectRowAtIndexPath which I can't use in storyboarded project.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
PetsViewController *pets = [[PetsViewController alloc] initWithNibName:#"PetsViewController" bundle:nil];
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Dog"]) {
pets.petsInt = 0;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Cat"]) {
pets.petsInt = 1;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Snake"]) {
pets.petsInt = 2;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
[self.navigationController pushViewController:pets animated:YES];
}
#end
PetsViewController.h
#import <UIKit/UIKit.h>
#interface PetsViewController : UITableViewController {
NSMutableArray *dogArray;
NSMutableArray *catArray;
NSMutableArray *snakeArray;
int petsInt;
}
#property int petsInt;
#end
PetsViewController.m
#import "PetsViewController.h"
#interface PetsViewController ()
#end
#implementation PetsViewController
#synthesize petsInt;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dogArray = [[NSMutableArray alloc] initWithObjects:#"HAF",#"hafo", #"hafinio", nil];
catArray = [[NSMutableArray alloc] initWithObjects:#"MYAU",#"myainio", #"mya lya lya", nil];
snakeArray = [[NSMutableArray alloc] initWithObjects:#"fshhhhh",#"fsssss", #"xrt", nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (petsInt == 0) return [dogArray count];
if (petsInt == 1) return [catArray count];
if (petsInt == 2) return [snakeArray count];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PetsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (petsInt == 0) cell.textLabel.text = [dogArray objectAtIndex:indexPath.row];
if (petsInt == 1) cell.textLabel.text = [catArray objectAtIndex:indexPath.row];
if (petsInt == 2) cell.textLabel.text = [snakeArray objectAtIndex:indexPath.row];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
[self performSegueWithIdentifier:#"SEGUE_NAME" sender:self];
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"SEGUE_NAME"]) {
PetsViewController *pets = [segue destinationViewController];
[pets setPetsInt:0];
[pets setTitle:#"Title"];
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 0;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 1;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 2;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 3;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
}
i have tried many ways and i finaly realized the right method, but it works only when under view did load method objects have only one description but if it hase something like thise
gazel = [[NSMutableArray alloc] init];
Data *data = [[Data alloc] init];
data.title = #"<էրեբունի> Օդանավակայան";
data.subtitle = #"Հարաֆ Արևմտյան Թաղամաս";
data.photo = 1;
[gazel addObject:data];
its not working
I have two views, the first (view A) is a table view. Every row has a disclosure button, when I click on the button I display the second view (view B) which is a table view too. When i click on a row, I want to pass the data to view A and display it as detailTextLabel.
#import <UIKit/UIKit.h>
#interface A : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSDictionary *listData;
NSArray *keys;
}
#property (nonatomic, retain) NSDictionary *listData;
#property (nonatomic, retain) NSArray *keys;
#end
#import "A.h"
#implementation A
#synthesize listData;
#synthesize keys;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[listData release];
[keys release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"Criteres" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.listData = dict;
[dict release];
NSArray *array = [[listData allKeys]sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
self.keys = array;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.listData = nil;
self.keys = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Table View Data Source Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [keys count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [listData objectForKey:key];
return [nameSection count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
return key;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [listData objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SectionsTableIdentifier] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
if (section == 0) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
if (row == 2)
cell.detailTextLabel.text = #"En m2";
if (row == 1)
cell.detailTextLabel.text = #"En €";
}
if (section == 1) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
}
return cell;
}
#pragma mark -
#pragma mark Table Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = 2;
return row;
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return indexPath;
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *ownerCell = [tableView cellForRowAtIndexPath:indexPath];
if ([ownerCell.textLabel.text isEqualToString:#"Ecole"]) {
B *prixview = [[B alloc]init];
[self.navigationController pushViewController:prixview animated:YES];
prixview.title = #"prix";
}
if ([ownerCell.textLabel.text isEqualToString:#"Crèche"]) {
B *prixview = [[B alloc]init];
[self.navigationController pushViewController:prixview animated:YES];
prixview.title = #"Prix";
}
}
#end
#import <UIKit/UIKit.h>
#interface B : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSArray *typetab;
NSInteger radioSelectionTypeBien;
NSString *radioSelectionTypeBienString;
}
#property (nonatomic, retain) NSArray *typetab;
#property (nonatomic, retain) NSString *radioSelectionTypeBienString;
#end
#import "B.h"
#implementation B
#synthesize typetab;
#synthesize radioSelectionTypeBienString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[self.radioSelectionTypeBienString release];
[self.typetab release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Critères"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(backButtonActionTypeBien:)];
self.navigationItem.leftBarButtonItem = backButton;
[backButton release];
radioSelectionTypeBien = -1;
NSArray *type = [[NSArray alloc]initWithObjects:#"Appartement",#"Maison",#"Commerce", nil ];
self.typetab = type;
[type release];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)backButtonActionTypeBien: (id)sender
{
[self.navigationController pushViewController:self.navigationController.parentViewController animated:YES];
}
- (void)viewDidUnload
{
self.radioSelectionTypeBienString = nil;
self.typetab = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.typetab count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [typetab objectAtIndex:indexPath.row];
if (indexPath.row == radioSelectionTypeBien){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
radioSelectionTypeBien = indexPath.row;
radioSelectionTypeBienString = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
[tableView reloadData];
}
#end
Usually i write a method in the controller B like:
-(voi)initVCwithString:(NSString*)_string andSomeObject:(NSObject *)_obj;
(so the controller B must have 2 ivar, a string and an object, that you have to set in this method)
then call this in your didSelectRowAtIndexPath: from the controller A
...
B _vcB=//alloc..init..etc
[_vcB initVCwithString:yourCell.textLabel.text andSomeObject:someObj];
[self.navigationController pushViewController:_vcB animated:YES];
[_vcB release];
Then in cellForRowAtIndexPath of B set cell.detailTextLabel.text=yourStringIvar;
Hope this helps.
Basically there are two possibilities that seems to be suitable. You can write a custom delegate method which pass the value to the A controller, or you can make a notification via notification centre, which can then assign the value to the A controller by catching the notification which will be triggered by picking a cell in the controller B.