Prepare navigationItem.title command behind
I'm still object c relative, so please refrain from me if this is a rookie question. I am trying to set the title of my nav controller to the appropriate object information. I use prepareforsegue method for this, but first time go to new controller, header is empty. If I try again it appears, but if I clicked something else it shows the name of the things I clicked earlier. I have added the code below.
//.h
#import <UIKit/UIKit.h>
@interface STATableViewController : UITableViewController
@property(strong,nonatomic)NSArray *listOfExercises;
@property(weak,nonatomic)NSString *navTitle;
@end
//.m
#import "STATableViewController.h"
#import "ExercisesViewController.h"
@implementation STATableViewController
@synthesize listOfExercises = _listOfExercises, navTitle = _navTitle;
- (void)viewDidLoad
{
[super viewDidLoad];
_listOfExercises = [NSArray arrayWithObjects:@"Raketstart",@"SpeedBåd",@"Træstamme",nil];
self.navigationItem.title = @"Exercises";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_listOfExercises 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];
}
NSString *cellValue = [_listOfExercises objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_navTitle = [_listOfExercises objectAtIndex:indexPath.row];
//NSLog(_navTitle);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:@"toExercise"])
{
ExercisesViewController *foo = [segue destinationViewController];
foo.navigationItem.title= _navTitle;
}
}
@end
source to share
This is because prepareForSegue:sender:
before is called tableView didSelectRowAtIndexPath:
. This way you always set your navigationItem title before you set your _navTitle resource with the value you want.
Instead of getting the title in the didSelectRowAtIndex path, do it in your finished form like this:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:@"toExercise"])
{
// "sender" is the table cell that was selected
UITableViewCell *cell = (UITableViewCell*)sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSString *title= [_listOfExercises objectAtIndex:indexPath.row];
ExercisesViewController *foo = [segue destinationViewController];
foo.navigationItem.title = title;
}
}
source to share