Jake
Jake

Reputation: 1295

How to get value of self.navigationItem.title and set as new variable?

On a detail view I'm trying to pull the navigation item's title which is dynamically set from my UITableView. I want to set it as an NSString value - so for example if my title is "potatoes" I want to get that string and set it as a variable in my view controller.

Here's the code I have so far. I tried setting this new variable as my UILabel text and it always outputs the string "Detail" - I can never seem to get the actual title value.

NSString *theTitleValue = self.navigationItem.title;
self.detailDescriptionLabel.text = theTitleValue;

I should point out that if I manually set a string to my description label (UILabel) it works fine. Only when I'm pulling the self.navigationitem.title does it come back as 'Detail'

self.detailDescriptionLabel.text = @"Some stuff here LMAO!!!";

So the single line above will output that string in my label. Any thoughts on how I can get the literal string value of my current navigation item?

EDIT: Here is the code from my table view which pushes this new detail view and title setting. Is there alternatively a way to pass this variable from the table view into the detail view?

What I mean is the value of currentLabel is exactly what I need to grab. However this code below is from MasterViewController.m and I need the currentLabel variable inside DetailViewController.m. I don't know of any way to pass variables between view controllers, so in my mind the easiest way to solve this would be pulling the value from the DetailViewController's navigation title.

# MasterViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    // creating NSString value for current vegetable in array
    NSString *currentLabel = [self.vegetablesListing objectAtIndex:indexPath.row];
    DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"VegetablesDetailViewCont"];

    [self.navigationController pushViewController:detailVC animated:YES];
    detailVC.navigationItem.title = currentLabel;
}

Upvotes: 2

Views: 2373

Answers (2)

Destiny Islands
Destiny Islands

Reputation: 46

What you could do is set the new UIViewController's title directly, even along with the navigation controller's title. Then in your new detail view just call self.title to pull out the value.

example codes:

DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewName"];
detailVC.title = currentLabel;
detailVC.navigationItem.title = currentLabel;

[self.navigationController pushViewController:detailVC animated:YES];

then in your detail controller you can check this value with NSLog:

NSLog(@"%@", self.title);

Upvotes: 3

Saurabh Passolia
Saurabh Passolia

Reputation: 8109

self.detailDescriptionLabel.text = self.navigationController.navigationBar.topItem.title;

Upvotes: 3

Related Questions